FormHelper.php 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225
  1. <?php
  2. /**
  3. * Automatic generation of HTML FORMs from given data.
  4. *
  5. * Used for scaffolding.
  6. *
  7. * PHP 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package cake.libs.view.helpers
  18. * @since CakePHP(tm) v 0.10.0.1076
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. App::uses('AppHelper', 'View/Helper');
  22. /**
  23. * Form helper library.
  24. *
  25. * Automatic generation of HTML FORMs from given data.
  26. *
  27. * @package cake.libs.view.helpers
  28. * @link http://book.cakephp.org/view/1383/Form
  29. */
  30. class FormHelper extends AppHelper {
  31. /**
  32. * Other helpers used by FormHelper
  33. *
  34. * @var array
  35. * @access public
  36. */
  37. public $helpers = array('Html');
  38. /**
  39. * Holds the fields array('field_name' => array('type'=> 'string', 'length'=> 100),
  40. * primaryKey and validates array('field_name')
  41. *
  42. * @access public
  43. */
  44. public $fieldset = array();
  45. /**
  46. * Options used by DateTime fields
  47. *
  48. * @var array
  49. */
  50. private $__options = array(
  51. 'day' => array(), 'minute' => array(), 'hour' => array(),
  52. 'month' => array(), 'year' => array(), 'meridian' => array()
  53. );
  54. /**
  55. * List of fields created, used with secure forms.
  56. *
  57. * @var array
  58. * @access public
  59. */
  60. public $fields = array();
  61. /**
  62. * Defines the type of form being created. Set by FormHelper::create().
  63. *
  64. * @var string
  65. * @access public
  66. */
  67. public $requestType = null;
  68. /**
  69. * The default model being used for the current form.
  70. *
  71. * @var string
  72. * @access public
  73. */
  74. public $defaultModel = null;
  75. /**
  76. * Persistent default options used by input(). Set by FormHelper::create().
  77. *
  78. * @var array
  79. * @access protected
  80. */
  81. protected $_inputDefaults = array();
  82. /**
  83. * Introspects model information and extracts information related
  84. * to validation, field length and field type. Appends information into
  85. * $this->fieldset.
  86. *
  87. * @return Model Returns a model instance
  88. */
  89. protected function &_introspectModel($model) {
  90. $object = null;
  91. if (is_string($model) && strpos($model, '.') !== false) {
  92. $path = explode('.', $model);
  93. $model = end($path);
  94. }
  95. if (ClassRegistry::isKeySet($model)) {
  96. $object = ClassRegistry::getObject($model);
  97. }
  98. if (!empty($object)) {
  99. $fields = $object->schema();
  100. foreach ($fields as $key => $value) {
  101. unset($fields[$key]);
  102. $fields[$key] = $value;
  103. }
  104. if (!empty($object->hasAndBelongsToMany)) {
  105. foreach ($object->hasAndBelongsToMany as $alias => $assocData) {
  106. $fields[$alias] = array('type' => 'multiple');
  107. }
  108. }
  109. $validates = array();
  110. if (!empty($object->validate)) {
  111. foreach ($object->validate as $validateField => $validateProperties) {
  112. if ($this->_isRequiredField($validateProperties)) {
  113. $validates[] = $validateField;
  114. }
  115. }
  116. }
  117. $defaults = array('fields' => array(), 'key' => 'id', 'validates' => array());
  118. $key = $object->primaryKey;
  119. $this->fieldset[$model] = array_merge($defaults, compact('fields', 'key', 'validates'));
  120. }
  121. return $object;
  122. }
  123. /**
  124. * Returns if a field is required to be filled based on validation properties from the validating object
  125. *
  126. * @return boolean true if field is required to be filled, false otherwise
  127. */
  128. protected function _isRequiredField($validateProperties) {
  129. $required = false;
  130. if (is_array($validateProperties)) {
  131. $dims = Set::countDim($validateProperties);
  132. if ($dims == 1 || ($dims == 2 && isset($validateProperties['rule']))) {
  133. $validateProperties = array($validateProperties);
  134. }
  135. foreach ($validateProperties as $rule => $validateProp) {
  136. if (isset($validateProp['allowEmpty']) && $validateProp['allowEmpty'] === true) {
  137. return false;
  138. }
  139. $rule = isset($validateProp['rule']) ? $validateProp['rule'] : false;
  140. $required = $rule || empty($validateProp);
  141. if ($required) {
  142. break;
  143. }
  144. }
  145. }
  146. return $required;
  147. }
  148. /**
  149. * Returns an HTML FORM element.
  150. *
  151. * ### Options:
  152. *
  153. * - `type` Form method defaults to POST
  154. * - `action` The controller action the form submits to, (optional).
  155. * - `url` The url the form submits to. Can be a string or a url array,
  156. * - `default` Allows for the creation of Ajax forms.
  157. * - `onsubmit` Used in conjunction with 'default' to create ajax forms.
  158. * - `inputDefaults` set the default $options for FormHelper::input(). Any options that would
  159. * be set when using FormHelper::input() can be set here. Options set with `inputDefaults`
  160. * can be overridden when calling input()
  161. * - `encoding` Set the accept-charset encoding for the form. Defaults to `Configure::read('App.encoding')`
  162. *
  163. * @access public
  164. * @param string $model The model object which the form is being defined for
  165. * @param array $options An array of html attributes and options.
  166. * @return string An formatted opening FORM tag.
  167. * @link http://book.cakephp.org/view/1384/Creating-Forms
  168. */
  169. function create($model = null, $options = array()) {
  170. $created = $id = false;
  171. $append = '';
  172. if (is_array($model) && empty($options)) {
  173. $options = $model;
  174. $model = null;
  175. }
  176. if (empty($model) && $model !== false && !empty($this->request['models'])) {
  177. $model = $this->request['models'][0];
  178. $this->defaultModel = $this->request['models'][0];
  179. } elseif (empty($model) && empty($this->request['models'])) {
  180. $model = false;
  181. }
  182. $models = ClassRegistry::keys();
  183. foreach ($models as $currentModel) {
  184. if (ClassRegistry::isKeySet($currentModel)) {
  185. $currentObject =& ClassRegistry::getObject($currentModel);
  186. if (is_a($currentObject, 'Model') && !empty($currentObject->validationErrors)) {
  187. $this->validationErrors[Inflector::camelize($currentModel)] =& $currentObject->validationErrors;
  188. }
  189. }
  190. }
  191. if ($model !== false) {
  192. $object = $this->_introspectModel($model);
  193. $this->setEntity($model . '.', true);
  194. }
  195. $modelEntity = $this->model();
  196. if ($model !== false && isset($this->fieldset[$modelEntity]['key'])) {
  197. $data = $this->fieldset[$modelEntity];
  198. $recordExists = (
  199. isset($this->request->data[$model]) &&
  200. !empty($this->request->data[$model][$data['key']]) &&
  201. !is_array($this->request->data[$model][$data['key']])
  202. );
  203. if ($recordExists) {
  204. $created = true;
  205. $id = $this->request->data[$model][$data['key']];
  206. }
  207. }
  208. $options = array_merge(array(
  209. 'type' => ($created && empty($options['action'])) ? 'put' : 'post',
  210. 'action' => null,
  211. 'url' => null,
  212. 'default' => true,
  213. 'encoding' => strtolower(Configure::read('App.encoding')),
  214. 'inputDefaults' => array()),
  215. $options);
  216. $this->_inputDefaults = $options['inputDefaults'];
  217. unset($options['inputDefaults']);
  218. if ($options['action'] === null && $options['url'] === null) {
  219. $options['action'] = $this->request->here(false);
  220. if (!isset($options['id'])) {
  221. $options['id'] = $this->domId($this->request['action'] . 'Form');
  222. }
  223. } elseif (empty($options['url']) || is_array($options['url'])) {
  224. if (empty($options['url']['controller'])) {
  225. if (!empty($model) && $model != $this->defaultModel) {
  226. $options['url']['controller'] = Inflector::underscore(Inflector::pluralize($model));
  227. } elseif (!empty($this->request->params['controller'])) {
  228. $options['url']['controller'] = Inflector::underscore($this->request->params['controller']);
  229. }
  230. }
  231. if (empty($options['action'])) {
  232. $options['action'] = $this->request->params['action'];
  233. }
  234. $actionDefaults = array(
  235. 'plugin' => $this->plugin,
  236. 'controller' => $this->_View->viewPath,
  237. 'action' => $options['action'],
  238. );
  239. if (!empty($options['action']) && !isset($options['id'])) {
  240. $options['id'] = $this->domId($options['action'] . 'Form');
  241. }
  242. $options['action'] = array_merge($actionDefaults, (array)$options['url']);
  243. if (empty($options['action'][0]) && !empty($id)) {
  244. $options['action'][0] = $id;
  245. }
  246. } elseif (is_string($options['url'])) {
  247. $options['action'] = $options['url'];
  248. }
  249. unset($options['url']);
  250. switch (strtolower($options['type'])) {
  251. case 'get':
  252. $htmlAttributes['method'] = 'get';
  253. break;
  254. case 'file':
  255. $htmlAttributes['enctype'] = 'multipart/form-data';
  256. $options['type'] = ($created) ? 'put' : 'post';
  257. case 'post':
  258. case 'put':
  259. case 'delete':
  260. $append .= $this->hidden('_method', array(
  261. 'name' => '_method', 'value' => strtoupper($options['type']), 'id' => null
  262. ));
  263. default:
  264. $htmlAttributes['method'] = 'post';
  265. break;
  266. }
  267. $this->requestType = strtolower($options['type']);
  268. $htmlAttributes['action'] = $this->url($options['action']);
  269. unset($options['type'], $options['action']);
  270. if ($options['default'] == false) {
  271. if (isset($htmlAttributes['onSubmit']) || isset($htmlAttributes['onsubmit'])) {
  272. $htmlAttributes['onsubmit'] .= ' event.returnValue = false; return false;';
  273. } else {
  274. $htmlAttributes['onsubmit'] = 'event.returnValue = false; return false;';
  275. }
  276. }
  277. if (!empty($options['encoding'])) {
  278. $htmlAttributes['accept-charset'] = $options['encoding'];
  279. unset($options['encoding']);
  280. }
  281. unset($options['default']);
  282. $htmlAttributes = array_merge($options, $htmlAttributes);
  283. $this->fields = array();
  284. if (isset($this->request->params['_Token']) && !empty($this->request->params['_Token'])) {
  285. $append .= $this->hidden('_Token.key', array(
  286. 'value' => $this->request->params['_Token']['key'], 'id' => 'Token' . mt_rand())
  287. );
  288. }
  289. if (!empty($append)) {
  290. $append = $this->Html->useTag('block', ' style="display:none;"', $append);
  291. }
  292. $this->setEntity($model . '.', true);
  293. return $this->Html->useTag('form', $htmlAttributes) . $append;
  294. }
  295. /**
  296. * Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden
  297. * input fields where appropriate.
  298. *
  299. * If $options is set a form submit button will be created. Options can be either a string or an array.
  300. *
  301. * {{{
  302. * array usage:
  303. *
  304. * array('label' => 'save'); value="save"
  305. * array('label' => 'save', 'name' => 'Whatever'); value="save" name="Whatever"
  306. * array('name' => 'Whatever'); value="Submit" name="Whatever"
  307. * array('label' => 'save', 'name' => 'Whatever', 'div' => 'good') <div class="good"> value="save" name="Whatever"
  308. * array('label' => 'save', 'name' => 'Whatever', 'div' => array('class' => 'good')); <div class="good"> value="save" name="Whatever"
  309. * }}}
  310. *
  311. * @param mixed $options as a string will use $options as the value of button,
  312. * @return string a closing FORM tag optional submit button.
  313. * @access public
  314. * @link http://book.cakephp.org/view/1389/Closing-the-Form
  315. */
  316. public function end($options = null) {
  317. if (!empty($this->request['models'])) {
  318. $models = $this->request['models'][0];
  319. }
  320. $out = null;
  321. $submit = null;
  322. if ($options !== null) {
  323. $submitOptions = array();
  324. if (is_string($options)) {
  325. $submit = $options;
  326. } else {
  327. if (isset($options['label'])) {
  328. $submit = $options['label'];
  329. unset($options['label']);
  330. }
  331. $submitOptions = $options;
  332. if (!$submit) {
  333. $submit = __('Submit');
  334. }
  335. }
  336. $out .= $this->submit($submit, $submitOptions);
  337. }
  338. if (isset($this->request['_Token']) && !empty($this->request['_Token'])) {
  339. $out .= $this->secure($this->fields);
  340. $this->fields = array();
  341. }
  342. $this->setEntity(null);
  343. $out .= $this->Html->useTag('formend');
  344. $this->_View->modelScope = false;
  345. return $out;
  346. }
  347. /**
  348. * Generates a hidden field with a security hash based on the fields used in the form.
  349. *
  350. * @param array $fields The list of fields to use when generating the hash
  351. * @return string A hidden input field with a security hash
  352. */
  353. public function secure($fields = array()) {
  354. if (!isset($this->request['_Token']) || empty($this->request['_Token'])) {
  355. return;
  356. }
  357. $locked = array();
  358. foreach ($fields as $key => $value) {
  359. if (!is_int($key)) {
  360. $locked[$key] = $value;
  361. unset($fields[$key]);
  362. }
  363. }
  364. sort($fields, SORT_STRING);
  365. ksort($locked, SORT_STRING);
  366. $fields += $locked;
  367. $fields = Security::hash(serialize($fields) . Configure::read('Security.salt'));
  368. $locked = implode(array_keys($locked), '|');
  369. $out = $this->hidden('_Token.fields', array(
  370. 'value' => urlencode($fields . ':' . $locked),
  371. 'id' => 'TokenFields' . mt_rand()
  372. ));
  373. return $this->Html->useTag('block', ' style="display:none;"', $out);
  374. }
  375. /**
  376. * Determine which fields of a form should be used for hash.
  377. * Populates $this->fields
  378. *
  379. * @param mixed $field Reference to field to be secured
  380. * @param mixed $value Field value, if value should not be tampered with.
  381. * @return void
  382. * @access private
  383. */
  384. function __secure($field = null, $value = null) {
  385. if (!$field) {
  386. $field = $this->_View->entity();
  387. } elseif (is_string($field)) {
  388. $field = Set::filter(explode('.', $field), true);
  389. }
  390. if (!empty($this->request['_Token']['disabledFields'])) {
  391. foreach ((array)$this->request['_Token']['disabledFields'] as $disabled) {
  392. $disabled = explode('.', $disabled);
  393. if (array_values(array_intersect($field, $disabled)) === $disabled) {
  394. return;
  395. }
  396. }
  397. }
  398. $field = implode('.', $field);
  399. if (!in_array($field, $this->fields)) {
  400. if ($value !== null) {
  401. return $this->fields[$field] = $value;
  402. }
  403. $this->fields[] = $field;
  404. }
  405. }
  406. /**
  407. * Returns true if there is an error for the given field, otherwise false
  408. *
  409. * @param string $field This should be "Modelname.fieldname"
  410. * @return boolean If there are errors this method returns true, else false.
  411. * @access public
  412. * @link http://book.cakephp.org/view/1426/isFieldError
  413. */
  414. public function isFieldError($field) {
  415. $this->setEntity($field);
  416. return (bool)$this->tagIsInvalid();
  417. }
  418. /**
  419. * Returns a formatted error message for given FORM field, NULL if no errors.
  420. *
  421. * ### Options:
  422. *
  423. * - `escape` bool Whether or not to html escape the contents of the error.
  424. * - `wrap` mixed Whether or not the error message should be wrapped in a div. If a
  425. * string, will be used as the HTML tag to use.
  426. * - `class` string The classname for the error message
  427. *
  428. * @param string $field A field name, like "Modelname.fieldname"
  429. * @param mixed $text Error message or array of $options. If array, `attributes` key
  430. * will get used as html attributes for error container
  431. * @param array $options Rendering options for <div /> wrapper tag
  432. * @return string If there are errors this method returns an error message, otherwise null.
  433. * @access public
  434. * @link http://book.cakephp.org/view/1423/error
  435. */
  436. public function error($field, $text = null, $options = array()) {
  437. $defaults = array('wrap' => true, 'class' => 'error-message', 'escape' => true);
  438. $options = array_merge($defaults, $options);
  439. $this->setEntity($field);
  440. if ($error = $this->tagIsInvalid()) {
  441. if (is_array($error)) {
  442. list(,,$field) = explode('.', $field);
  443. if (isset($error[$field])) {
  444. $error = $error[$field];
  445. } else {
  446. return null;
  447. }
  448. }
  449. if (is_array($text) && is_numeric($error) && $error > 0) {
  450. $error--;
  451. }
  452. if (is_array($text)) {
  453. $options = array_merge($options, array_intersect_key($text, $defaults));
  454. if (isset($text['attributes']) && is_array($text['attributes'])) {
  455. $options = array_merge($options, $text['attributes']);
  456. }
  457. $text = isset($text[$error]) ? $text[$error] : null;
  458. unset($options[$error]);
  459. }
  460. if ($text != null) {
  461. $error = $text;
  462. } elseif (is_numeric($error)) {
  463. $error = __('Error in field %s', Inflector::humanize($this->field()));
  464. }
  465. if ($options['escape']) {
  466. $error = h($error);
  467. unset($options['escape']);
  468. }
  469. if ($options['wrap']) {
  470. $tag = is_string($options['wrap']) ? $options['wrap'] : 'div';
  471. unset($options['wrap']);
  472. return $this->Html->tag($tag, $error, $options);
  473. } else {
  474. return $error;
  475. }
  476. } else {
  477. return null;
  478. }
  479. }
  480. /**
  481. * Returns a formatted LABEL element for HTML FORMs. Will automatically generate
  482. * a for attribute if one is not provided.
  483. *
  484. * @param string $fieldName This should be "Modelname.fieldname"
  485. * @param string $text Text that will appear in the label field.
  486. * @param mixed $options An array of HTML attributes, or a string, to be used as a class name.
  487. * @return string The formatted LABEL element
  488. * @link http://book.cakephp.org/view/1427/label
  489. */
  490. function label($fieldName = null, $text = null, $options = array()) {
  491. if (empty($fieldName)) {
  492. $fieldName = implode('.', $this->_View->entity());
  493. }
  494. if ($text === null) {
  495. if (strpos($fieldName, '.') !== false) {
  496. $fieldElements = explode('.', $fieldName);
  497. $text = array_pop($fieldElements);
  498. } else {
  499. $text = $fieldName;
  500. }
  501. if (substr($text, -3) == '_id') {
  502. $text = substr($text, 0, strlen($text) - 3);
  503. }
  504. $text = __(Inflector::humanize(Inflector::underscore($text)));
  505. }
  506. if (is_string($options)) {
  507. $options = array('class' => $options);
  508. }
  509. if (isset($options['for'])) {
  510. $labelFor = $options['for'];
  511. unset($options['for']);
  512. } else {
  513. $labelFor = $this->domId($fieldName);
  514. }
  515. return $this->Html->useTag('label', $labelFor, $options, $text);
  516. }
  517. /**
  518. * Generate a set of inputs for `$fields`. If $fields is null the current model
  519. * will be used.
  520. *
  521. * In addition to controller fields output, `$fields` can be used to control legend
  522. * and fieldset rendering with the `fieldset` and `legend` keys.
  523. * `$form->inputs(array('legend' => 'My legend'));` Would generate an input set with
  524. * a custom legend. You can customize individual inputs through `$fields` as well.
  525. *
  526. * {{{
  527. * $form->inputs(array(
  528. * 'name' => array('label' => 'custom label')
  529. * ));
  530. * }}}
  531. *
  532. * In addition to fields control, inputs() allows you to use a few additional options.
  533. *
  534. * - `fieldset` Set to false to disable the fieldset. If a string is supplied it will be used as
  535. * the classname for the fieldset element.
  536. * - `legend` Set to false to disable the legend for the generated input set. Or supply a string
  537. * to customize the legend text.
  538. *
  539. * @param mixed $fields An array of fields to generate inputs for, or null.
  540. * @param array $blacklist a simple array of fields to not create inputs for.
  541. * @return string Completed form inputs.
  542. */
  543. public function inputs($fields = null, $blacklist = null) {
  544. $fieldset = $legend = true;
  545. $model = $this->model();
  546. if (is_array($fields)) {
  547. if (array_key_exists('legend', $fields)) {
  548. $legend = $fields['legend'];
  549. unset($fields['legend']);
  550. }
  551. if (isset($fields['fieldset'])) {
  552. $fieldset = $fields['fieldset'];
  553. unset($fields['fieldset']);
  554. }
  555. } elseif ($fields !== null) {
  556. $fieldset = $legend = $fields;
  557. if (!is_bool($fieldset)) {
  558. $fieldset = true;
  559. }
  560. $fields = array();
  561. }
  562. if (empty($fields)) {
  563. $fields = array_keys($this->fieldset[$model]['fields']);
  564. }
  565. if ($legend === true) {
  566. $actionName = __('New %s');
  567. $isEdit = (
  568. strpos($this->request->params['action'], 'update') !== false ||
  569. strpos($this->request->params['action'], 'edit') !== false
  570. );
  571. if ($isEdit) {
  572. $actionName = __('Edit %s');
  573. }
  574. $modelName = Inflector::humanize(Inflector::underscore($model));
  575. $legend = sprintf($actionName, __($modelName));
  576. }
  577. $out = null;
  578. foreach ($fields as $name => $options) {
  579. if (is_numeric($name) && !is_array($options)) {
  580. $name = $options;
  581. $options = array();
  582. }
  583. $entity = explode('.', $name);
  584. $blacklisted = (
  585. is_array($blacklist) &&
  586. (in_array($name, $blacklist) || in_array(end($entity), $blacklist))
  587. );
  588. if ($blacklisted) {
  589. continue;
  590. }
  591. $out .= $this->input($name, $options);
  592. }
  593. if (is_string($fieldset)) {
  594. $fieldsetClass = sprintf(' class="%s"', $fieldset);
  595. } else {
  596. $fieldsetClass = '';
  597. }
  598. if ($fieldset && $legend) {
  599. return $this->Html->useTag('fieldset', $fieldsetClass, $this->Html->useTag('legend', $legend) . $out);
  600. } elseif ($fieldset) {
  601. return $this->Html->useTag('fieldset', $fieldsetClass, $out);
  602. } else {
  603. return $out;
  604. }
  605. }
  606. /**
  607. * Generates a form input element complete with label and wrapper div
  608. *
  609. * ### Options
  610. *
  611. * See each field type method for more information. Any options that are part of
  612. * $attributes or $options for the different **type** methods can be included in `$options` for input().
  613. *
  614. * - `type` - Force the type of widget you want. e.g. `type => 'select'`
  615. * - `label` - Either a string label, or an array of options for the label. See FormHelper::label()
  616. * - `div` - Either `false` to disable the div, or an array of options for the div.
  617. * See HtmlHelper::div() for more options.
  618. * - `options` - for widgets that take options e.g. radio, select
  619. * - `error` - control the error message that is produced
  620. * - `empty` - String or boolean to enable empty select box options.
  621. * - `before` - Content to place before the label + input.
  622. * - `after` - Content to place after the label + input.
  623. * - `between` - Content to place between the label + input.
  624. * - `format` - format template for element order. Any element that is not in the array, will not be in the output.
  625. * - Default input format order: array('before', 'label', 'between', 'input', 'after', 'error')
  626. * - Default checkbox format order: array('before', 'input', 'between', 'label', 'after', 'error')
  627. * - Hidden input will not be formatted
  628. * - Radio buttons cannot have the order of input and label elements controlled with these settings.
  629. *
  630. * @param string $fieldName This should be "Modelname.fieldname"
  631. * @param array $options Each type of input takes different options.
  632. * @return string Completed form widget.
  633. * @access public
  634. * @link http://book.cakephp.org/view/1390/Automagic-Form-Elements
  635. */
  636. public function input($fieldName, $options = array()) {
  637. $this->setEntity($fieldName);
  638. $options = array_merge(
  639. array('before' => null, 'between' => null, 'after' => null, 'format' => null),
  640. $this->_inputDefaults,
  641. $options
  642. );
  643. $modelKey = $this->model();
  644. $fieldKey = $this->field();
  645. if (!isset($this->fieldset[$modelKey])) {
  646. $this->_introspectModel($modelKey);
  647. }
  648. if (!isset($options['type'])) {
  649. $magicType = true;
  650. $options['type'] = 'text';
  651. if (isset($options['options'])) {
  652. $options['type'] = 'select';
  653. } elseif (in_array($fieldKey, array('psword', 'passwd', 'password'))) {
  654. $options['type'] = 'password';
  655. } elseif (isset($options['checked'])) {
  656. $options['type'] = 'checkbox';
  657. } elseif (isset($this->fieldset[$modelKey]['fields'][$fieldKey])) {
  658. $fieldDef = $this->fieldset[$modelKey]['fields'][$fieldKey];
  659. $type = $fieldDef['type'];
  660. $primaryKey = $this->fieldset[$modelKey]['key'];
  661. }
  662. if (isset($type)) {
  663. $map = array(
  664. 'string' => 'text', 'datetime' => 'datetime',
  665. 'boolean' => 'checkbox', 'timestamp' => 'datetime',
  666. 'text' => 'textarea', 'time' => 'time',
  667. 'date' => 'date', 'float' => 'text'
  668. );
  669. if (isset($this->map[$type])) {
  670. $options['type'] = $this->map[$type];
  671. } elseif (isset($map[$type])) {
  672. $options['type'] = $map[$type];
  673. }
  674. if ($fieldKey == $primaryKey) {
  675. $options['type'] = 'hidden';
  676. }
  677. }
  678. if (preg_match('/_id$/', $fieldKey) && $options['type'] !== 'hidden') {
  679. $options['type'] = 'select';
  680. }
  681. if ($modelKey === $fieldKey) {
  682. $options['type'] = 'select';
  683. if (!isset($options['multiple'])) {
  684. $options['multiple'] = 'multiple';
  685. }
  686. }
  687. }
  688. $types = array('checkbox', 'radio', 'select');
  689. if (
  690. (!isset($options['options']) && in_array($options['type'], $types)) ||
  691. (isset($magicType) && $options['type'] == 'text')
  692. ) {
  693. $varName = Inflector::variable(
  694. Inflector::pluralize(preg_replace('/_id$/', '', $fieldKey))
  695. );
  696. $varOptions = $this->_View->getVar($varName);
  697. if (is_array($varOptions)) {
  698. if ($options['type'] !== 'radio') {
  699. $options['type'] = 'select';
  700. }
  701. $options['options'] = $varOptions;
  702. }
  703. }
  704. $autoLength = (!array_key_exists('maxlength', $options) && isset($fieldDef['length']));
  705. if ($autoLength && $options['type'] == 'text') {
  706. $options['maxlength'] = $fieldDef['length'];
  707. }
  708. if ($autoLength && $fieldDef['type'] == 'float') {
  709. $options['maxlength'] = array_sum(explode(',', $fieldDef['length']))+1;
  710. }
  711. $divOptions = array();
  712. $div = $this->_extractOption('div', $options, true);
  713. unset($options['div']);
  714. if (!empty($div)) {
  715. $divOptions['class'] = 'input';
  716. $divOptions = $this->addClass($divOptions, $options['type']);
  717. if (is_string($div)) {
  718. $divOptions['class'] = $div;
  719. } elseif (is_array($div)) {
  720. $divOptions = array_merge($divOptions, $div);
  721. }
  722. if (
  723. isset($this->fieldset[$modelKey]) &&
  724. in_array($fieldKey, $this->fieldset[$modelKey]['validates'])
  725. ) {
  726. $divOptions = $this->addClass($divOptions, 'required');
  727. }
  728. if (!isset($divOptions['tag'])) {
  729. $divOptions['tag'] = 'div';
  730. }
  731. }
  732. $label = null;
  733. if (isset($options['label']) && $options['type'] !== 'radio') {
  734. $label = $options['label'];
  735. unset($options['label']);
  736. }
  737. if ($options['type'] === 'radio') {
  738. $label = false;
  739. if (isset($options['options'])) {
  740. $radioOptions = (array)$options['options'];
  741. unset($options['options']);
  742. }
  743. }
  744. if ($label !== false) {
  745. $label = $this->_inputLabel($fieldName, $label, $options);
  746. }
  747. $error = $this->_extractOption('error', $options, null);
  748. unset($options['error']);
  749. $selected = $this->_extractOption('selected', $options, null);
  750. unset($options['selected']);
  751. if (isset($options['rows']) || isset($options['cols'])) {
  752. $options['type'] = 'textarea';
  753. }
  754. if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time' || $options['type'] === 'select') {
  755. $options += array('empty' => false);
  756. }
  757. if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time') {
  758. $dateFormat = $this->_extractOption('dateFormat', $options, 'MDY');
  759. $timeFormat = $this->_extractOption('timeFormat', $options, 12);
  760. unset($options['dateFormat'], $options['timeFormat']);
  761. }
  762. $type = $options['type'];
  763. $out = array_merge(
  764. array('before' => null, 'label' => null, 'between' => null, 'input' => null, 'after' => null, 'error' => null),
  765. array('before' => $options['before'], 'label' => $label, 'between' => $options['between'], 'after' => $options['after'])
  766. );
  767. $format = null;
  768. if (is_array($options['format']) && in_array('input', $options['format'])) {
  769. $format = $options['format'];
  770. }
  771. unset($options['type'], $options['before'], $options['between'], $options['after'], $options['format']);
  772. switch ($type) {
  773. case 'hidden':
  774. $input = $this->hidden($fieldName, $options);
  775. $format = array('input');
  776. unset($divOptions);
  777. break;
  778. case 'checkbox':
  779. $input = $this->checkbox($fieldName, $options);
  780. $format = $format ? $format : array('before', 'input', 'between', 'label', 'after', 'error');
  781. break;
  782. case 'radio':
  783. $input = $this->radio($fieldName, $radioOptions, $options);
  784. break;
  785. case 'file':
  786. $input = $this->file($fieldName, $options);
  787. break;
  788. case 'select':
  789. $options += array('options' => array(), 'value' => $selected);
  790. $list = $options['options'];
  791. unset($options['options']);
  792. $input = $this->select($fieldName, $list, $options);
  793. break;
  794. case 'time':
  795. $options['value'] = $selected;
  796. $input = $this->dateTime($fieldName, null, $timeFormat, $options);
  797. break;
  798. case 'date':
  799. $options['value'] = $selected;
  800. $input = $this->dateTime($fieldName, $dateFormat, null, $options);
  801. break;
  802. case 'datetime':
  803. $options['value'] = $selected;
  804. $input = $this->dateTime($fieldName, $dateFormat, $timeFormat, $options);
  805. break;
  806. case 'textarea':
  807. $input = $this->textarea($fieldName, $options + array('cols' => '30', 'rows' => '6'));
  808. break;
  809. default:
  810. $input = $this->{$type}($fieldName, $options);
  811. }
  812. if ($type != 'hidden' && $error !== false) {
  813. $errMsg = $this->error($fieldName, $error);
  814. if ($errMsg) {
  815. $divOptions = $this->addClass($divOptions, 'error');
  816. $out['error'] = $errMsg;
  817. }
  818. }
  819. $out['input'] = $input;
  820. $format = $format ? $format : array('before', 'label', 'between', 'input', 'after', 'error');
  821. $output = '';
  822. foreach ($format as $element) {
  823. $output .= $out[$element];
  824. unset($out[$element]);
  825. }
  826. if (!empty($divOptions['tag'])) {
  827. $tag = $divOptions['tag'];
  828. unset($divOptions['tag']);
  829. $output = $this->Html->tag($tag, $output, $divOptions);
  830. }
  831. return $output;
  832. }
  833. /**
  834. * Extracts a single option from an options array.
  835. *
  836. * @param string $name The name of the option to pull out.
  837. * @param array $options The array of options you want to extract.
  838. * @param mixed $default The default option value
  839. * @return the contents of the option or default
  840. */
  841. protected function _extractOption($name, $options, $default = null) {
  842. if (array_key_exists($name, $options)) {
  843. return $options[$name];
  844. }
  845. return $default;
  846. }
  847. /**
  848. * Generate a label for an input() call.
  849. *
  850. * @param array $options Options for the label element.
  851. * @return string Generated label element
  852. */
  853. protected function _inputLabel($fieldName, $label, $options) {
  854. $labelAttributes = $this->domId(array(), 'for');
  855. if ($options['type'] === 'date' || $options['type'] === 'datetime') {
  856. if (isset($options['dateFormat']) && $options['dateFormat'] === 'NONE') {
  857. $labelAttributes['for'] .= 'Hour';
  858. $idKey = 'hour';
  859. } else {
  860. $labelAttributes['for'] .= 'Month';
  861. $idKey = 'month';
  862. }
  863. if (isset($options['id']) && isset($options['id'][$idKey])) {
  864. $labelAttributes['for'] = $options['id'][$idKey];
  865. }
  866. } elseif ($options['type'] === 'time') {
  867. $labelAttributes['for'] .= 'Hour';
  868. if (isset($options['id']) && isset($options['id']['hour'])) {
  869. $labelAttributes['for'] = $options['id']['hour'];
  870. }
  871. }
  872. if (is_array($label)) {
  873. $labelText = null;
  874. if (isset($label['text'])) {
  875. $labelText = $label['text'];
  876. unset($label['text']);
  877. }
  878. $labelAttributes = array_merge($labelAttributes, $label);
  879. } else {
  880. $labelText = $label;
  881. }
  882. if (isset($options['id']) && is_string($options['id'])) {
  883. $labelAttributes = array_merge($labelAttributes, array('for' => $options['id']));
  884. }
  885. return $this->label($fieldName, $labelText, $labelAttributes);
  886. }
  887. /**
  888. * Creates a checkbox input widget.
  889. *
  890. * ### Options:
  891. *
  892. * - `value` - the value of the checkbox
  893. * - `checked` - boolean indicate that this checkbox is checked.
  894. * - `hiddenField` - boolean to indicate if you want the results of checkbox() to include
  895. * a hidden input with a value of ''.
  896. * - `disabled` - create a disabled input.
  897. *
  898. * @param string $fieldName Name of a field, like this "Modelname.fieldname"
  899. * @param array $options Array of HTML attributes.
  900. * @return string An HTML text input element.
  901. * @access public
  902. * @link http://book.cakephp.org/view/1414/checkbox
  903. */
  904. public function checkbox($fieldName, $options = array()) {
  905. $options = $this->_initInputField($fieldName, $options) + array('hiddenField' => true);
  906. $value = current($this->value());
  907. $output = "";
  908. if (empty($options['value'])) {
  909. $options['value'] = 1;
  910. } elseif (
  911. (!isset($options['checked']) && !empty($value) && $value === $options['value']) ||
  912. !empty($options['checked'])
  913. ) {
  914. $options['checked'] = 'checked';
  915. }
  916. if ($options['hiddenField']) {
  917. $hiddenOptions = array(
  918. 'id' => $options['id'] . '_', 'name' => $options['name'],
  919. 'value' => '0', 'secure' => false
  920. );
  921. if (isset($options['disabled']) && $options['disabled'] == true) {
  922. $hiddenOptions['disabled'] = 'disabled';
  923. }
  924. $output = $this->hidden($fieldName, $hiddenOptions);
  925. }
  926. unset($options['hiddenField']);
  927. return $output . $this->Html->useTag('checkbox', $options['name'], array_diff_key($options, array('name' => '')));
  928. }
  929. /**
  930. * Creates a set of radio widgets. Will create a legend and fieldset
  931. * by default. Use $options to control this
  932. *
  933. * ### Attributes:
  934. *
  935. * - `separator` - define the string in between the radio buttons
  936. * - `legend` - control whether or not the widget set has a fieldset & legend
  937. * - `value` - indicate a value that is should be checked
  938. * - `label` - boolean to indicate whether or not labels for widgets show be displayed
  939. * - `hiddenField` - boolean to indicate if you want the results of radio() to include
  940. * a hidden input with a value of ''. This is useful for creating radio sets that non-continuous
  941. *
  942. * @param string $fieldName Name of a field, like this "Modelname.fieldname"
  943. * @param array $options Radio button options array.
  944. * @param array $attributes Array of HTML attributes, and special attributes above.
  945. * @return string Completed radio widget set.
  946. * @access public
  947. * @link http://book.cakephp.org/view/1429/radio
  948. */
  949. public function radio($fieldName, $options = array(), $attributes = array()) {
  950. $attributes = $this->_initInputField($fieldName, $attributes);
  951. $legend = false;
  952. if (isset($attributes['legend'])) {
  953. $legend = $attributes['legend'];
  954. unset($attributes['legend']);
  955. } elseif (count($options) > 1) {
  956. $legend = __(Inflector::humanize($this->field()));
  957. }
  958. $label = true;
  959. if (isset($attributes['label'])) {
  960. $label = $attributes['label'];
  961. unset($attributes['label']);
  962. }
  963. $inbetween = null;
  964. if (isset($attributes['separator'])) {
  965. $inbetween = $attributes['separator'];
  966. unset($attributes['separator']);
  967. }
  968. if (isset($attributes['value'])) {
  969. $value = $attributes['value'];
  970. } else {
  971. $value = $this->value($fieldName);
  972. }
  973. $out = array();
  974. $hiddenField = isset($attributes['hiddenField']) ? $attributes['hiddenField'] : true;
  975. unset($attributes['hiddenField']);
  976. foreach ($options as $optValue => $optTitle) {
  977. $optionsHere = array('value' => $optValue);
  978. if (isset($value) && $optValue == $value) {
  979. $optionsHere['checked'] = 'checked';
  980. }
  981. $tagName = Inflector::camelize(
  982. $attributes['id'] . '_' . Inflector::slug($optValue)
  983. );
  984. if ($label) {
  985. $optTitle = $this->Html->useTag('label', $tagName, '', $optTitle);
  986. }
  987. $allOptions = array_merge($attributes, $optionsHere);
  988. $out[] = $this->Html->useTag('radio', $attributes['name'], $tagName,
  989. array_diff_key($allOptions, array('name' => '', 'type' => '', 'id' => '')),
  990. $optTitle
  991. );
  992. }
  993. $hidden = null;
  994. if ($hiddenField) {
  995. if (!isset($value) || $value === '') {
  996. $hidden = $this->hidden($fieldName, array(
  997. 'id' => $attributes['id'] . '_', 'value' => '', 'name' => $attributes['name']
  998. ));
  999. }
  1000. }
  1001. $out = $hidden . implode($inbetween, $out);
  1002. if ($legend) {
  1003. $out = $this->Html->useTag('fieldset', '', $this->Html->useTag('legend', $legend) . $out);
  1004. }
  1005. return $out;
  1006. }
  1007. /**
  1008. * Missing method handler - implements various simple input types. Is used to create inputs
  1009. * of various types. e.g. `$this->Form->text();` will create `<input type="text" />` while
  1010. * `$this->Form->range();` will create `<input type="range" />`
  1011. *
  1012. * ### Usage
  1013. *
  1014. * `$this->Form->search('User.query', array('value' => 'test'));`
  1015. *
  1016. * Will make an input like:
  1017. *
  1018. * `<input type="search" id="UserQuery" name="data[User][query]" value="test" />`
  1019. *
  1020. * The first argument to an input type should always be the fieldname, in `Model.field` format.
  1021. * The second argument should always be an array of attributes for the input.
  1022. *
  1023. * @param string $method Method name / input type to make.
  1024. * @param array $params Parameters for the method call
  1025. * @return string Formatted input method.
  1026. * @throws CakeException When there are no params for the method call.
  1027. */
  1028. public function __call($method, $params) {
  1029. $options = array();
  1030. if (empty($params)) {
  1031. throw new CakeException(__('Missing field name for FormHelper::%s', $method));
  1032. }
  1033. if (isset($params[1])) {
  1034. $options = $params[1];
  1035. }
  1036. if (!isset($options['type'])) {
  1037. $options['type'] = $method;
  1038. }
  1039. $options = $this->_initInputField($params[0], $options);
  1040. return $this->Html->useTag('input', $options['name'], array_diff_key($options, array('name' => '')));
  1041. }
  1042. /**
  1043. * Creates a textarea widget.
  1044. *
  1045. * ### Options:
  1046. *
  1047. * - `escape` - Whether or not the contents of the textarea should be escaped. Defaults to true.
  1048. *
  1049. * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
  1050. * @param array $options Array of HTML attributes, and special options above.
  1051. * @return string A generated HTML text input element
  1052. * @access public
  1053. * @link http://book.cakephp.org/view/1433/textarea
  1054. */
  1055. public function textarea($fieldName, $options = array()) {
  1056. $options = $this->_initInputField($fieldName, $options);
  1057. $value = null;
  1058. if (array_key_exists('value', $options)) {
  1059. $value = $options['value'];
  1060. if (!array_key_exists('escape', $options) || $options['escape'] !== false) {
  1061. $value = h($value);
  1062. }
  1063. unset($options['value']);
  1064. }
  1065. return $this->Html->useTag('textarea', $options['name'], array_diff_key($options, array('type' => '', 'name' => '')), $value);
  1066. }
  1067. /**
  1068. * Creates a hidden input field.
  1069. *
  1070. * @param string $fieldName Name of a field, in the form of "Modelname.fieldname"
  1071. * @param array $options Array of HTML attributes.
  1072. * @return string A generated hidden input
  1073. * @access public
  1074. * @link http://book.cakephp.org/view/1425/hidden
  1075. */
  1076. public function hidden($fieldName, $options = array()) {
  1077. $secure = true;
  1078. if (isset($options['secure'])) {
  1079. $secure = $options['secure'];
  1080. unset($options['secure']);
  1081. }
  1082. $options = $this->_initInputField($fieldName, array_merge(
  1083. $options, array('secure' => false)
  1084. ));
  1085. $model = $this->model();
  1086. if ($fieldName !== '_method' && $model !== '_Token' && $secure) {
  1087. $this->__secure(null, '' . $options['value']);
  1088. }
  1089. return $this->Html->useTag('hidden', $options['name'], array_diff_key($options, array('name' => '', 'class' => '')));
  1090. }
  1091. /**
  1092. * Creates file input widget.
  1093. *
  1094. * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
  1095. * @param array $options Array of HTML attributes.
  1096. * @return string A generated file input.
  1097. * @access public
  1098. * @link http://book.cakephp.org/view/1424/file
  1099. */
  1100. public function file($fieldName, $options = array()) {
  1101. $options = array_merge($options, array('secure' => false));
  1102. $options = $this->_initInputField($fieldName, $options);
  1103. $field = $this->_View->entity();
  1104. foreach (array('name', 'type', 'tmp_name', 'error', 'size') as $suffix) {
  1105. $this->__secure(array_merge($field, array($suffix)));
  1106. }
  1107. return $this->Html->useTag('file', $options['name'], array_diff_key($options, array('name' => '')));
  1108. }
  1109. /**
  1110. * Creates a `<button>` tag. The type attribute defaults to `type="submit"`
  1111. * You can change it to a different value by using `$options['type']`.
  1112. *
  1113. * ### Options:
  1114. *
  1115. * - `escape` - HTML entity encode the $title of the button. Defaults to false.
  1116. *
  1117. * @param string $title The button's caption. Not automatically HTML encoded
  1118. * @param array $options Array of options and HTML attributes.
  1119. * @return string A HTML button tag.
  1120. * @access public
  1121. * @link http://book.cakephp.org/view/1415/button
  1122. */
  1123. public function button($title, $options = array()) {
  1124. $options += array('type' => 'submit', 'escape' => false);
  1125. if ($options['escape']) {
  1126. $title = h($title);
  1127. }
  1128. return $this->Html->useTag('button', $options['type'], array_diff_key($options, array('type' => '')), $title);
  1129. }
  1130. /**
  1131. * Create a `<button>` tag with `<form>` using POST method.
  1132. *
  1133. * This method creates an element <form>. So do not use this method in some opened form.
  1134. *
  1135. * ### Options:
  1136. *
  1137. * - `data` - Array with key/value to pass in input hidden
  1138. * - Other options is the same of button method.
  1139. *
  1140. * @param string $title The button's caption. Not automatically HTML encoded
  1141. * @param mixed $url URL as string or array
  1142. * @param array $options Array of options and HTML attributes.
  1143. * @return string A HTML button tag.
  1144. */
  1145. public function postButton($title, $url, $options = array()) {
  1146. $out = $this->create(false, array('id' => false, 'url' => $url, 'style' => 'display:none;'));
  1147. if (isset($options['data']) && is_array($options['data'])) {
  1148. foreach ($options['data'] as $key => $value) {
  1149. $out .= $this->hidden($key, array('value' => $value, 'id' => false));
  1150. }
  1151. unset($options['data']);
  1152. }
  1153. $out .= $this->button($title, $options);
  1154. $out .= $this->end();
  1155. return $out;
  1156. }
  1157. /**
  1158. * Creates an HTML link, but access the url using method POST. Requires javascript enabled in browser.
  1159. *
  1160. * This method creates an element <form>. So do not use this method in some opened form.
  1161. *
  1162. * ### Options:
  1163. *
  1164. * - `data` - Array with key/value to pass in input hidden
  1165. * - Other options is the same of HtmlHelper::link() method.
  1166. * - The option `onclick` will be replaced.
  1167. *
  1168. * @param string $title The content to be wrapped by <a> tags.
  1169. * @param mixed $url Cake-relative URL or array of URL parameters, or external URL (starts with http://)
  1170. * @param array $options Array of HTML attributes.
  1171. * @param string $confirmMessage JavaScript confirmation message.
  1172. * @return string An `<a />` element.
  1173. */
  1174. public function postLink($title, $url = null, $options = array(), $confirmMessage = false) {
  1175. if (!empty($options['confirm'])) {
  1176. $confirmMessage = $options['confirm'];
  1177. unset($options['confirm']);
  1178. }
  1179. $formName = uniqid('post_');
  1180. $out = $this->create(false, array('url' => $url, 'name' => $formName, 'id' => $formName, 'style' => 'display:none;'));
  1181. if (isset($options['data']) && is_array($options['data'])) {
  1182. foreach ($options['data'] as $key => $value) {
  1183. $out .= $this->hidden($key, array('value' => $value, 'id' => false));
  1184. }
  1185. unset($options['data']);
  1186. }
  1187. $out .= $this->end();
  1188. $url = '#';
  1189. $onClick = 'document.' . $formName . '.submit();';
  1190. if ($confirmMessage) {
  1191. $confirmMessage = str_replace(array("'", '"'), array("\'", '\"'), $confirmMessage);
  1192. $options['onclick'] = "if (confirm('{$confirmMessage}')) { {$onClick} }";
  1193. } else {
  1194. $options['onclick'] = $onClick;
  1195. }
  1196. $options['onclick'] .= ' event.returnValue = false; return false;';
  1197. $out .= $this->Html->link($title, $url, $options);
  1198. return $out;
  1199. }
  1200. /**
  1201. * Creates a submit button element. This method will generate `<input />` elements that
  1202. * can be used to submit, and reset forms by using $options. image submits can be created by supplying an
  1203. * image path for $caption.
  1204. *
  1205. * ### Options
  1206. *
  1207. * - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to
  1208. * FormHelper::input().
  1209. * - `before` - Content to include before the input.
  1210. * - `after` - Content to include after the input.
  1211. * - `type` - Set to 'reset' for reset inputs. Defaults to 'submit'
  1212. * - Other attributes will be assigned to the input element.
  1213. *
  1214. * ### Options
  1215. *
  1216. * - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to
  1217. * FormHelper::input().
  1218. * - Other attributes will be assigned to the input element.
  1219. *
  1220. * @param string $caption The label appearing on the button OR if string contains :// or the
  1221. * extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension
  1222. * exists, AND the first character is /, image is relative to webroot,
  1223. * OR if the first character is not /, image is relative to webroot/img.
  1224. * @param array $options Array of options. See above.
  1225. * @return string A HTML submit button
  1226. * @access public
  1227. * @link http://book.cakephp.org/view/1431/submit
  1228. */
  1229. public function submit($caption = null, $options = array()) {
  1230. if (!$caption) {
  1231. $caption = __('Submit');
  1232. }
  1233. $out = null;
  1234. $div = true;
  1235. if (isset($options['div'])) {
  1236. $div = $options['div'];
  1237. unset($options['div']);
  1238. }
  1239. $options += array('type' => 'submit', 'before' => null, 'after' => null);
  1240. $divOptions = array('tag' => 'div');
  1241. if ($div === true) {
  1242. $divOptions['class'] = 'submit';
  1243. } elseif ($div === false) {
  1244. unset($divOptions);
  1245. } elseif (is_string($div)) {
  1246. $divOptions['class'] = $div;
  1247. } elseif (is_array($div)) {
  1248. $divOptions = array_merge(array('class' => 'submit', 'tag' => 'div'), $div);
  1249. }
  1250. $before = $options['before'];
  1251. $after = $options['after'];
  1252. unset($options['before'], $options['after']);
  1253. if (strpos($caption, '://') !== false) {
  1254. unset($options['type']);
  1255. $out .= $before . $this->Html->useTag('submitimage', $caption, $options) . $after;
  1256. } elseif (preg_match('/\.(jpg|jpe|jpeg|gif|png|ico)$/', $caption)) {
  1257. unset($options['type']);
  1258. if ($caption{0} !== '/') {
  1259. $url = $this->webroot(IMAGES_URL . $caption);
  1260. } else {
  1261. $caption = trim($caption, '/');
  1262. $url = $this->webroot($caption);
  1263. }
  1264. $out .= $before . $this->Html->useTag('submitimage', $url, $options) . $after;
  1265. } else {
  1266. $options['value'] = $caption;
  1267. $out .= $before . $this->Html->useTag('submit', $options) . $after;
  1268. }
  1269. if (isset($divOptions)) {
  1270. $tag = $divOptions['tag'];
  1271. unset($divOptions['tag']);
  1272. $out = $this->Html->tag($tag, $out, $divOptions);
  1273. }
  1274. return $out;
  1275. }
  1276. /**
  1277. * Returns a formatted SELECT element.
  1278. *
  1279. * ### Attributes:
  1280. *
  1281. * - `showParents` - If included in the array and set to true, an additional option element
  1282. * will be added for the parent of each option group. You can set an option with the same name
  1283. * and it's key will be used for the value of the option.
  1284. * - `multiple` - show a multiple select box. If set to 'checkbox' multiple checkboxes will be
  1285. * created instead.
  1286. * - `empty` - If true, the empty select option is shown. If a string,
  1287. * that string is displayed as the empty element.
  1288. * - `escape` - If true contents of options will be HTML entity encoded. Defaults to true.
  1289. * - `value` The selected value of the input.
  1290. * - `class` - When using multiple = checkbox the classname to apply to the divs. Defaults to 'checkbox'.
  1291. *
  1292. * ### Using options
  1293. *
  1294. * A simple array will create normal options:
  1295. *
  1296. * {{{
  1297. * $options = array(1 => 'one', 2 => 'two);
  1298. * $this->Form->select('Model.field', $options));
  1299. * }}}
  1300. *
  1301. * While a nested options array will create optgroups with options inside them.
  1302. * {{{
  1303. * $options = array(
  1304. * 1 => 'bill',
  1305. * 'fred' => array(
  1306. * 2 => 'fred',
  1307. * 3 => 'fred jr.'
  1308. * )
  1309. * );
  1310. * $this->Form->select('Model.field', $options);
  1311. * }}}
  1312. *
  1313. * In the above `2 => 'fred'` will not generate an option element. You should enable the `showParents`
  1314. * attribute to show the fred option.
  1315. *
  1316. * @param string $fieldName Name attribute of the SELECT
  1317. * @param array $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the
  1318. * SELECT element
  1319. * @param array $attributes The HTML attributes of the select element.
  1320. * @return string Formatted SELECT element
  1321. * @access public
  1322. * @link http://book.cakephp.org/view/1430/select
  1323. */
  1324. public function select($fieldName, $options = array(), $attributes = array()) {
  1325. $select = array();
  1326. $style = null;
  1327. $tag = null;
  1328. $attributes += array(
  1329. 'class' => null,
  1330. 'escape' => true,
  1331. 'secure' => null,
  1332. 'empty' => '',
  1333. 'showParents' => false
  1334. );
  1335. $escapeOptions = $this->_extractOption('escape', $attributes);
  1336. $secure = $this->_extractOption('secure', $attributes);
  1337. $showEmpty = $this->_extractOption('empty', $attributes);
  1338. $showParents = $this->_extractOption('showParents', $attributes);
  1339. unset($attributes['escape'], $attributes['secure'], $attributes['empty'], $attributes['showParents']);
  1340. $attributes = $this->_initInputField($fieldName, array_merge(
  1341. (array)$attributes, array('secure' => false)
  1342. ));
  1343. if (is_string($options) && isset($this->__options[$options])) {
  1344. $options = $this->__generateOptions($options);
  1345. } elseif (!is_array($options)) {
  1346. $options = array();
  1347. }
  1348. if (isset($attributes['type'])) {
  1349. unset($attributes['type']);
  1350. }
  1351. if (isset($attributes) && array_key_exists('multiple', $attributes)) {
  1352. $style = ($attributes['multiple'] === 'checkbox') ? 'checkbox' : null;
  1353. $template = ($style) ? 'checkboxmultiplestart' : 'selectmultiplestart';
  1354. $tag = $template;
  1355. $hiddenAttributes = array(
  1356. 'value' => '',
  1357. 'id' => $attributes['id'] . ($style ? '' : '_'),
  1358. 'secure' => false,
  1359. 'name' => $attributes['name']
  1360. );
  1361. $select[] = $this->hidden(null, $hiddenAttributes);
  1362. } else {
  1363. $tag = 'selectstart';
  1364. }
  1365. if (!empty($tag) || isset($template)) {
  1366. if (!isset($secure) || $secure == true) {
  1367. $this->__secure();
  1368. }
  1369. $select[] = $this->Html->useTag($tag, $attributes['name'], array_diff_key($attributes, array('name' => '', 'value' => '')));
  1370. }
  1371. $emptyMulti = (
  1372. $showEmpty !== null && $showEmpty !== false && !(
  1373. empty($showEmpty) && (isset($attributes) &&
  1374. array_key_exists('multiple', $attributes))
  1375. )
  1376. );
  1377. if ($emptyMulti) {
  1378. $showEmpty = ($showEmpty === true) ? '' : $showEmpty;
  1379. $options = array_reverse($options, true);
  1380. $options[''] = $showEmpty;
  1381. $options = array_reverse($options, true);
  1382. }
  1383. $select = array_merge($select, $this->__selectOptions(
  1384. array_reverse($options, true),
  1385. array(),
  1386. $showParents,
  1387. array('escape' => $escapeOptions, 'style' => $style, 'name' => $attributes['name'], 'value' => $attributes['value'], 'class' => $attributes['class'])
  1388. ));
  1389. $template = ($style == 'checkbox') ? 'checkboxmultipleend' : 'selectend';
  1390. $select[] = $this->Html->useTag($template);
  1391. return implode("\n", $select);
  1392. }
  1393. /**
  1394. * Returns a SELECT element for days.
  1395. *
  1396. * ### Attributes:
  1397. *
  1398. * - `empty` - If true, the empty select option is shown. If a string,
  1399. * that string is displayed as the empty element.
  1400. * - `value` The selected value of the input.
  1401. *
  1402. * @param string $fieldName Prefix name for the SELECT element
  1403. * @param array $attributes HTML attributes for the select element
  1404. * @return string A generated day select box.
  1405. * @access public
  1406. * @link http://book.cakephp.org/view/1419/day
  1407. */
  1408. public function day($fieldName = null, $attributes = array()) {
  1409. $attributes += array('empty' => true, 'value' => null);
  1410. $attributes = $this->__dateTimeSelected('day', $fieldName, $attributes);
  1411. if (strlen($attributes['value']) > 2) {
  1412. $attributes['value'] = date('d', strtotime($attributes['value']));
  1413. } elseif ($attributes['value'] === false) {
  1414. $attributes['value'] = null;
  1415. }
  1416. return $this->select($fieldName . ".day", $this->__generateOptions('day'), $attributes);
  1417. }
  1418. /**
  1419. * Returns a SELECT element for years
  1420. *
  1421. * ### Attributes:
  1422. *
  1423. * - `empty` - If true, the empty select option is shown. If a string,
  1424. * that string is displayed as the empty element.
  1425. * - `orderYear` - Ordering of year values in select options.
  1426. * Possible values 'asc', 'desc'. Default 'desc'
  1427. * - `value` The selected value of the input.
  1428. *
  1429. * @param string $fieldName Prefix name for the SELECT element
  1430. * @param integer $minYear First year in sequence
  1431. * @param integer $maxYear Last year in sequence
  1432. * @param array $attributes Attribute array for the select elements.
  1433. * @return string Completed year select input
  1434. * @access public
  1435. * @link http://book.cakephp.org/view/1416/year
  1436. */
  1437. public function year($fieldName, $minYear = null, $maxYear = null, $attributes = array()) {
  1438. $attributes += array('empty' => true, 'value' => null);
  1439. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  1440. if (is_array($value)) {
  1441. extract($value);
  1442. $attributes['value'] = $year;
  1443. } else {
  1444. if (empty($value)) {
  1445. if (!$attributes['empty'] && !$maxYear) {
  1446. $attributes['value'] = 'now';
  1447. } elseif (!$attributes['empty'] && $maxYear && !$attributes['value']) {
  1448. $attributes['value'] = $maxYear;
  1449. }
  1450. } else {
  1451. $attributes['value'] = $value;
  1452. }
  1453. }
  1454. }
  1455. if (strlen($attributes['value']) > 4 || $attributes['value'] === 'now') {
  1456. $attributes['value'] = date('Y', strtotime($attributes['value']));
  1457. } elseif ($attributes['value'] === false) {
  1458. $attributes['value'] = null;
  1459. }
  1460. $yearOptions = array('min' => $minYear, 'max' => $maxYear, 'order' => 'desc');
  1461. if (isset($attributes['orderYear'])) {
  1462. $yearOptions['order'] = $attributes['orderYear'];
  1463. unset($attributes['orderYear']);
  1464. }
  1465. return $this->select(
  1466. $fieldName . '.year', $this->__generateOptions('year', $yearOptions),
  1467. $attributes
  1468. );
  1469. }
  1470. /**
  1471. * Returns a SELECT element for months.
  1472. *
  1473. * ### Attributes:
  1474. *
  1475. * - `monthNames` - If false, 2 digit numbers will be used instead of text.
  1476. * If a array, the given array will be used.
  1477. * - `empty` - If true, the empty select option is shown. If a string,
  1478. * that string is displayed as the empty element.
  1479. * - `value` The selected value of the input.
  1480. *
  1481. * @param string $fieldName Prefix name for the SELECT element
  1482. * @param array $attributes Attributes for the select element
  1483. * @return string A generated month select dropdown.
  1484. * @access public
  1485. * @link http://book.cakephp.org/view/1417/month
  1486. */
  1487. public function month($fieldName, $attributes = array()) {
  1488. $attributes += array('empty' => true, 'value' => null);
  1489. $attributes = $this->__dateTimeSelected('month', $fieldName, $attributes);
  1490. if (strlen($attributes['value']) > 2) {
  1491. $attributes['value'] = date('m', strtotime($attributes['value']));
  1492. } elseif ($attributes['value'] === false) {
  1493. $attributes['value'] = null;
  1494. }
  1495. $defaults = array('monthNames' => true);
  1496. $attributes = array_merge($defaults, (array) $attributes);
  1497. $monthNames = $attributes['monthNames'];
  1498. unset($attributes['monthNames']);
  1499. return $this->select(
  1500. $fieldName . ".month",
  1501. $this->__generateOptions('month', array('monthNames' => $monthNames)),
  1502. $attributes
  1503. );
  1504. }
  1505. /**
  1506. * Returns a SELECT element for hours.
  1507. *
  1508. * ### Attributes:
  1509. *
  1510. * - `empty` - If true, the empty select option is shown. If a string,
  1511. * that string is displayed as the empty element.
  1512. * - `value` The selected value of the input.
  1513. *
  1514. * @param string $fieldName Prefix name for the SELECT element
  1515. * @param boolean $format24Hours True for 24 hours format
  1516. * @param array $attributes List of HTML attributes
  1517. * @return string Completed hour select input
  1518. * @access public
  1519. * @link http://book.cakephp.org/view/1420/hour
  1520. */
  1521. public function hour($fieldName, $format24Hours = false, $attributes = array()) {
  1522. $attributes += array('empty' => true, 'value' => null);
  1523. $attributes = $this->__dateTimeSelected('hour', $fieldName, $attributes);
  1524. if (strlen($attributes['value']) > 2) {
  1525. if ($format24Hours) {
  1526. $attributes['value'] = date('H', strtotime($attributes['value']));
  1527. } else {
  1528. $attributes['value'] = date('g', strtotime($attributes['value']));
  1529. }
  1530. } elseif ($attributes['value'] === false) {
  1531. $attributes['value'] = null;
  1532. }
  1533. return $this->select(
  1534. $fieldName . ".hour",
  1535. $this->__generateOptions($format24Hours ? 'hour24' : 'hour'),
  1536. $attributes
  1537. );
  1538. }
  1539. /**
  1540. * Returns a SELECT element for minutes.
  1541. *
  1542. * ### Attributes:
  1543. *
  1544. * - `empty` - If true, the empty select option is shown. If a string,
  1545. * that string is displayed as the empty element.
  1546. * - `value` The selected value of the input.
  1547. *
  1548. * @param string $fieldName Prefix name for the SELECT element
  1549. * @param string $attributes Array of Attributes
  1550. * @return string Completed minute select input.
  1551. * @access public
  1552. * @link http://book.cakephp.org/view/1421/minute
  1553. */
  1554. public function minute($fieldName, $attributes = array()) {
  1555. $attributes += array('empty' => true, 'value' => null);
  1556. $attributes = $this->__dateTimeSelected('min', $fieldName, $attributes);
  1557. if (strlen($attributes['value']) > 2) {
  1558. $attributes['value'] = date('i', strtotime($attributes['value']));
  1559. } elseif ($attributes['value'] === false) {
  1560. $attributes['value'] = null;
  1561. }
  1562. $minuteOptions = array();
  1563. if (isset($attributes['interval'])) {
  1564. $minuteOptions['interval'] = $attributes['interval'];
  1565. unset($attributes['interval']);
  1566. }
  1567. return $this->select(
  1568. $fieldName . ".min", $this->__generateOptions('minute', $minuteOptions),
  1569. $attributes
  1570. );
  1571. }
  1572. /**
  1573. * Selects values for dateTime selects.
  1574. *
  1575. * @param string $select Name of element field. ex. 'day'
  1576. * @param string $fieldName Name of fieldName being generated ex. Model.created
  1577. * @param array $attributes Array of attributes, must contain 'empty' key.
  1578. * @return array Attributes array with currently selected value.
  1579. * @access private
  1580. */
  1581. function __dateTimeSelected($select, $fieldName, $attributes) {
  1582. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  1583. if (is_array($value) && isset($value[$select])) {
  1584. $attributes['value'] = $value[$select];
  1585. } else {
  1586. if (empty($value)) {
  1587. if (!$attributes['empty']) {
  1588. $attributes['value'] = 'now';
  1589. }
  1590. } else {
  1591. $attributes['value'] = $value;
  1592. }
  1593. }
  1594. }
  1595. return $attributes;
  1596. }
  1597. /**
  1598. * Returns a SELECT element for AM or PM.
  1599. *
  1600. * ### Attributes:
  1601. *
  1602. * - `empty` - If true, the empty select option is shown. If a string,
  1603. * that string is displayed as the empty element.
  1604. * - `value` The selected value of the input.
  1605. *
  1606. * @param string $fieldName Prefix name for the SELECT element
  1607. * @param string $attributes Array of Attributes
  1608. * @param bool $showEmpty Show/Hide an empty option
  1609. * @return string Completed meridian select input
  1610. * @access public
  1611. * @link http://book.cakephp.org/view/1422/meridian
  1612. */
  1613. public function meridian($fieldName, $attributes = array()) {
  1614. $attributes += array('empty' => true, 'value' => null);
  1615. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  1616. if (is_array($value)) {
  1617. extract($value);
  1618. $attributes['value'] = $meridian;
  1619. } else {
  1620. if (empty($value)) {
  1621. if (!$attribues['empty']) {
  1622. $attributes['value'] = date('a');
  1623. }
  1624. } else {
  1625. $attributes['value'] = date('a', strtotime($value));
  1626. }
  1627. }
  1628. }
  1629. if ($attributes['value'] === false) {
  1630. $attributes['value'] = null;
  1631. }
  1632. return $this->select(
  1633. $fieldName . ".meridian", $this->__generateOptions('meridian'),
  1634. $attributes
  1635. );
  1636. }
  1637. /**
  1638. * Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
  1639. *
  1640. * ### Attributes:
  1641. *
  1642. * - `monthNames` If false, 2 digit numbers will be used instead of text.
  1643. * If a array, the given array will be used.
  1644. * - `minYear` The lowest year to use in the year select
  1645. * - `maxYear` The maximum year to use in the year select
  1646. * - `interval` The interval for the minutes select. Defaults to 1
  1647. * - `separator` The contents of the string between select elements. Defaults to '-'
  1648. * - `empty` - If true, the empty select option is shown. If a string,
  1649. * that string is displayed as the empty element.
  1650. * - `value` | `default` The default value to be used by the input. A value in `$this->data`
  1651. * matching the field name will override this value. If no default is provided `time()` will be used.
  1652. *
  1653. * @param string $fieldName Prefix name for the SELECT element
  1654. * @param string $dateFormat DMY, MDY, YMD.
  1655. * @param string $timeFormat 12, 24.
  1656. * @param string $attributes array of Attributes
  1657. * @return string Generated set of select boxes for the date and time formats chosen.
  1658. * @access public
  1659. * @link http://book.cakephp.org/view/1418/dateTime
  1660. */
  1661. public function dateTime($fieldName, $dateFormat = 'DMY', $timeFormat = '12', $attributes = array()) {
  1662. $attributes += array('empty' => true, 'value' => null);
  1663. $year = $month = $day = $hour = $min = $meridian = null;
  1664. if (empty($attributes['value'])) {
  1665. $attributes = $this->value($attributes, $fieldName);
  1666. }
  1667. if ($attributes['value'] === null && $attributes['empty'] != true) {
  1668. $attributes['value'] = time();
  1669. }
  1670. if (!empty($attributes['value'])) {
  1671. if (is_array($attributes['value'])) {
  1672. extract($attributes['value']);
  1673. } else {
  1674. if (is_numeric($attributes['value'])) {
  1675. $attributes['value'] = strftime('%Y-%m-%d %H:%M:%S', $attributes['value']);
  1676. }
  1677. $meridian = 'am';
  1678. $pos = strpos($attributes['value'], '-');
  1679. if ($pos !== false) {
  1680. $date = explode('-', $attributes['value']);
  1681. $days = explode(' ', $date[2]);
  1682. $day = $days[0];
  1683. $month = $date[1];
  1684. $year = $date[0];
  1685. } else {
  1686. $days[1] = $attributes['value'];
  1687. }
  1688. if (!empty($timeFormat)) {
  1689. $time = explode(':', $days[1]);
  1690. $check = str_replace(':', '', $days[1]);
  1691. if (($check > 115959) && $timeFormat == '12') {
  1692. $time[0] = $time[0] - 12;
  1693. $meridian = 'pm';
  1694. } elseif ($time[0] == '00' && $timeFormat == '12') {
  1695. $time[0] = 12;
  1696. } elseif ($time[0] > 12) {
  1697. $meridian = 'pm';
  1698. }
  1699. if ($time[0] == 0 && $timeFormat == '12') {
  1700. $time[0] = 12;
  1701. }
  1702. $hour = $min = null;
  1703. if (isset($time[1])) {
  1704. $hour = $time[0];
  1705. $min = $time[1];
  1706. }
  1707. }
  1708. }
  1709. }
  1710. $elements = array('Day', 'Month', 'Year', 'Hour', 'Minute', 'Meridian');
  1711. $defaults = array(
  1712. 'minYear' => null, 'maxYear' => null, 'separator' => '-',
  1713. 'interval' => 1, 'monthNames' => true
  1714. );
  1715. $attributes = array_merge($defaults, (array) $attributes);
  1716. if (isset($attributes['minuteInterval'])) {
  1717. $attributes['interval'] = $attributes['minuteInterval'];
  1718. unset($attributes['minuteInterval']);
  1719. }
  1720. $minYear = $attributes['minYear'];
  1721. $maxYear = $attributes['maxYear'];
  1722. $separator = $attributes['separator'];
  1723. $interval = $attributes['interval'];
  1724. $monthNames = $attributes['monthNames'];
  1725. $attributes = array_diff_key($attributes, $defaults);
  1726. if (isset($attributes['id'])) {
  1727. if (is_string($attributes['id'])) {
  1728. // build out an array version
  1729. foreach ($elements as $element) {
  1730. $selectAttrName = 'select' . $element . 'Attr';
  1731. ${$selectAttrName} = $attributes;
  1732. ${$selectAttrName}['id'] = $attributes['id'] . $element;
  1733. }
  1734. } elseif (is_array($attributes['id'])) {
  1735. // check for missing ones and build selectAttr for each element
  1736. $attributes['id'] += array(
  1737. 'month' => '', 'year' => '', 'day' => '',
  1738. 'hour' => '', 'minute' => '', 'meridian' => ''
  1739. );
  1740. foreach ($elements as $element) {
  1741. $selectAttrName = 'select' . $element . 'Attr';
  1742. ${$selectAttrName} = $attributes;
  1743. ${$selectAttrName}['id'] = $attributes['id'][strtolower($element)];
  1744. }
  1745. }
  1746. } else {
  1747. // build the selectAttrName with empty id's to pass
  1748. foreach ($elements as $element) {
  1749. $selectAttrName = 'select' . $element . 'Attr';
  1750. ${$selectAttrName} = $attributes;
  1751. }
  1752. }
  1753. $selects = array();
  1754. foreach (preg_split('//', $dateFormat, -1, PREG_SPLIT_NO_EMPTY) as $char) {
  1755. switch ($char) {
  1756. case 'Y':
  1757. $selectYearAttr['value'] = $year;
  1758. $selects[] = $this->year(
  1759. $fieldName, $minYear, $maxYear, $selectYearAttr
  1760. );
  1761. break;
  1762. case 'M':
  1763. $selectMonthAttr['value'] = $month;
  1764. $selectMonthAttr['monthNames'] = $monthNames;
  1765. $selects[] = $this->month($fieldName, $selectMonthAttr);
  1766. break;
  1767. case 'D':
  1768. $selectDayAttr['value'] = $day;
  1769. $selects[] = $this->day($fieldName, $selectDayAttr);
  1770. break;
  1771. }
  1772. }
  1773. $opt = implode($separator, $selects);
  1774. if (!empty($interval) && $interval > 1 && !empty($min)) {
  1775. $min = round($min * (1 / $interval)) * $interval;
  1776. }
  1777. $selectMinuteAttr['interval'] = $interval;
  1778. switch ($timeFormat) {
  1779. case '24':
  1780. $selectHourAttr['value'] = $hour;
  1781. $selectMinuteAttr['value'] = $min;
  1782. $opt .= $this->hour($fieldName, true, $selectHourAttr) . ':' .
  1783. $this->minute($fieldName, $selectMinuteAttr);
  1784. break;
  1785. case '12':
  1786. $selectHourAttr['value'] = $hour;
  1787. $selectMinuteAttr['value'] = $min;
  1788. $selectMeridianAttr['value'] = $meridian;
  1789. $opt .= $this->hour($fieldName, false, $selectHourAttr) . ':' .
  1790. $this->minute($fieldName, $selectMinuteAttr) . ' ' .
  1791. $this->meridian($fieldName, $selectMeridianAttr);
  1792. break;
  1793. default:
  1794. $opt .= '';
  1795. break;
  1796. }
  1797. return $opt;
  1798. }
  1799. /**
  1800. * Gets the input field name for the current tag
  1801. *
  1802. * @param array $options
  1803. * @param string $key
  1804. * @return array
  1805. */
  1806. protected function _name($options = array(), $field = null, $key = 'name') {
  1807. if ($this->requestType == 'get') {
  1808. if ($options === null) {
  1809. $options = array();
  1810. } elseif (is_string($options)) {
  1811. $field = $options;
  1812. $options = 0;
  1813. }
  1814. if (!empty($field)) {
  1815. $this->setEntity($field);
  1816. }
  1817. if (is_array($options) && isset($options[$key])) {
  1818. return $options;
  1819. }
  1820. $name = !empty($this->_View->field) ? $this->_View->field : $this->_View->model;
  1821. if (!empty($this->_View->fieldSuffix)) {
  1822. $name .= '[' . $this->_View->fieldSuffix . ']';
  1823. }
  1824. if (is_array($options)) {
  1825. $options[$key] = $name;
  1826. return $options;
  1827. } else {
  1828. return $name;
  1829. }
  1830. }
  1831. return parent::_name($options, $field, $key);
  1832. }
  1833. /**
  1834. * Returns an array of formatted OPTION/OPTGROUP elements
  1835. * @access private
  1836. * @return array
  1837. */
  1838. function __selectOptions($elements = array(), $parents = array(), $showParents = null, $attributes = array()) {
  1839. $select = array();
  1840. $attributes = array_merge(
  1841. array('escape' => true, 'style' => null, 'value' => null, 'class' => null),
  1842. $attributes
  1843. );
  1844. $selectedIsEmpty = ($attributes['value'] === '' || $attributes['value'] === null);
  1845. $selectedIsArray = is_array($attributes['value']);
  1846. foreach ($elements as $name => $title) {
  1847. $htmlOptions = array();
  1848. if (is_array($title) && (!isset($title['name']) || !isset($title['value']))) {
  1849. if (!empty($name)) {
  1850. if ($attributes['style'] === 'checkbox') {
  1851. $select[] = $this->Html->useTag('fieldsetend');
  1852. } else {
  1853. $select[] = $this->Html->useTag('optiongroupend');
  1854. }
  1855. $parents[] = $name;
  1856. }
  1857. $select = array_merge($select, $this->__selectOptions(
  1858. $title, $parents, $showParents, $attributes
  1859. ));
  1860. if (!empty($name)) {
  1861. $name = $attributes['escape'] ? h($name) : $name;
  1862. if ($attributes['style'] === 'checkbox') {
  1863. $select[] = $this->Html->useTag('fieldsetstart', $name);
  1864. } else {
  1865. $select[] = $this->Html->useTag('optiongroup', $name, '');
  1866. }
  1867. }
  1868. $name = null;
  1869. } elseif (is_array($title)) {
  1870. $htmlOptions = $title;
  1871. $name = $title['value'];
  1872. $title = $title['name'];
  1873. unset($htmlOptions['name'], $htmlOptions['value']);
  1874. }
  1875. if ($name !== null) {
  1876. if (
  1877. (!$selectedIsArray && !$selectedIsEmpty && (string)$attributes['value'] == (string)$name) ||
  1878. ($selectedIsArray && in_array($name, $attributes['value']))
  1879. ) {
  1880. if ($attributes['style'] === 'checkbox') {
  1881. $htmlOptions['checked'] = true;
  1882. } else {
  1883. $htmlOptions['selected'] = 'selected';
  1884. }
  1885. }
  1886. if ($showParents || (!in_array($title, $parents))) {
  1887. $title = ($attributes['escape']) ? h($title) : $title;
  1888. if ($attributes['style'] === 'checkbox') {
  1889. $htmlOptions['value'] = $name;
  1890. $tagName = Inflector::camelize(
  1891. $this->model() . '_' . $this->field().'_'.Inflector::slug($name)
  1892. );
  1893. $htmlOptions['id'] = $tagName;
  1894. $label = array('for' => $tagName);
  1895. if (isset($htmlOptions['checked']) && $htmlOptions['checked'] === true) {
  1896. $label['class'] = 'selected';
  1897. }
  1898. $name = $attributes['name'];
  1899. if (empty($attributes['class'])) {
  1900. $attributes['class'] = 'checkbox';
  1901. }
  1902. $label = $this->label(null, $title, $label);
  1903. $item = $this->Html->useTag('checkboxmultiple', $name, $htmlOptions);
  1904. $select[] = $this->Html->div($attributes['class'], $item . $label);
  1905. } else {
  1906. $select[] = $this->Html->useTag('selectoption', $name, $htmlOptions, $title);
  1907. }
  1908. }
  1909. }
  1910. }
  1911. return array_reverse($select, true);
  1912. }
  1913. /**
  1914. * Generates option lists for common <select /> menus
  1915. * @access private
  1916. */
  1917. function __generateOptions($name, $options = array()) {
  1918. if (!empty($this->options[$name])) {
  1919. return $this->options[$name];
  1920. }
  1921. $data = array();
  1922. switch ($name) {
  1923. case 'minute':
  1924. if (isset($options['interval'])) {
  1925. $interval = $options['interval'];
  1926. } else {
  1927. $interval = 1;
  1928. }
  1929. $i = 0;
  1930. while ($i < 60) {
  1931. $data[sprintf('%02d', $i)] = sprintf('%02d', $i);
  1932. $i += $interval;
  1933. }
  1934. break;
  1935. case 'hour':
  1936. for ($i = 1; $i <= 12; $i++) {
  1937. $data[sprintf('%02d', $i)] = $i;
  1938. }
  1939. break;
  1940. case 'hour24':
  1941. for ($i = 0; $i <= 23; $i++) {
  1942. $data[sprintf('%02d', $i)] = $i;
  1943. }
  1944. break;
  1945. case 'meridian':
  1946. $data = array('am' => 'am', 'pm' => 'pm');
  1947. break;
  1948. case 'day':
  1949. $min = 1;
  1950. $max = 31;
  1951. if (isset($options['min'])) {
  1952. $min = $options['min'];
  1953. }
  1954. if (isset($options['max'])) {
  1955. $max = $options['max'];
  1956. }
  1957. for ($i = $min; $i <= $max; $i++) {
  1958. $data[sprintf('%02d', $i)] = $i;
  1959. }
  1960. break;
  1961. case 'month':
  1962. if ($options['monthNames'] === true) {
  1963. $data['01'] = __('January');
  1964. $data['02'] = __('February');
  1965. $data['03'] = __('March');
  1966. $data['04'] = __('April');
  1967. $data['05'] = __('May');
  1968. $data['06'] = __('June');
  1969. $data['07'] = __('July');
  1970. $data['08'] = __('August');
  1971. $data['09'] = __('September');
  1972. $data['10'] = __('October');
  1973. $data['11'] = __('November');
  1974. $data['12'] = __('December');
  1975. } else if (is_array($options['monthNames'])) {
  1976. $data = $options['monthNames'];
  1977. } else {
  1978. for ($m = 1; $m <= 12; $m++) {
  1979. $data[sprintf("%02s", $m)] = strftime("%m", mktime(1, 1, 1, $m, 1, 1999));
  1980. }
  1981. }
  1982. break;
  1983. case 'year':
  1984. $current = intval(date('Y'));
  1985. if (!isset($options['min'])) {
  1986. $min = $current - 20;
  1987. } else {
  1988. $min = $options['min'];
  1989. }
  1990. if (!isset($options['max'])) {
  1991. $max = $current + 20;
  1992. } else {
  1993. $max = $options['max'];
  1994. }
  1995. if ($min > $max) {
  1996. list($min, $max) = array($max, $min);
  1997. }
  1998. for ($i = $min; $i <= $max; $i++) {
  1999. $data[$i] = $i;
  2000. }
  2001. if ($options['order'] != 'asc') {
  2002. $data = array_reverse($data, true);
  2003. }
  2004. break;
  2005. }
  2006. $this->__options[$name] = $data;
  2007. return $this->__options[$name];
  2008. }
  2009. /**
  2010. * Sets field defaults and adds field to form security input hash
  2011. *
  2012. * ### Options
  2013. *
  2014. * - `secure` - boolean whether or not the field should be added to the security fields.
  2015. *
  2016. * @param string $field Name of the field to initialize options for.
  2017. * @param array $options Array of options to append options into.
  2018. * @return array Array of options for the input.
  2019. */
  2020. protected function _initInputField($field, $options = array()) {
  2021. if (isset($options['secure'])) {
  2022. $secure = $options['secure'];
  2023. unset($options['secure']);
  2024. } else {
  2025. $secure = (isset($this->request['_Token']) && !empty($this->request['_Token']));
  2026. }
  2027. $fieldName = null;
  2028. if ($secure && !empty($options['name'])) {
  2029. preg_match_all('/\[(.*?)\]/', $options['name'], $matches);
  2030. if (isset($matches[1])) {
  2031. $fieldName = $matches[1];
  2032. }
  2033. }
  2034. $result = parent::_initInputField($field, $options);
  2035. if ($secure) {
  2036. $this->__secure($fieldName);
  2037. }
  2038. return $result;
  2039. }
  2040. }