PageRenderTime 137ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/View/Helper/FormHelper.php

https://github.com/baidushine/cakephp
PHP | 2861 lines | 2158 code | 151 blank | 552 comment | 245 complexity | cf8d6520067166e8fe274a456deb56b8 MD5 | raw file
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @package Cake.View.Helper
  13. * @since CakePHP(tm) v 0.10.0.1076
  14. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  15. */
  16. App::uses('ClassRegistry', 'Utility');
  17. App::uses('AppHelper', 'View/Helper');
  18. App::uses('Hash', 'Utility');
  19. /**
  20. * Form helper library.
  21. *
  22. * Automatic generation of HTML FORMs from given data.
  23. *
  24. * @package Cake.View.Helper
  25. * @property HtmlHelper $Html
  26. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html
  27. */
  28. class FormHelper extends AppHelper {
  29. /**
  30. * Other helpers used by FormHelper
  31. *
  32. * @var array
  33. */
  34. public $helpers = array('Html');
  35. /**
  36. * Options used by DateTime fields
  37. *
  38. * @var array
  39. */
  40. protected $_options = array(
  41. 'day' => array(), 'minute' => array(), 'hour' => array(),
  42. 'month' => array(), 'year' => array(), 'meridian' => array()
  43. );
  44. /**
  45. * List of fields created, used with secure forms.
  46. *
  47. * @var array
  48. */
  49. public $fields = array();
  50. /**
  51. * Constant used internally to skip the securing process,
  52. * and neither add the field to the hash or to the unlocked fields.
  53. *
  54. * @var string
  55. */
  56. const SECURE_SKIP = 'skip';
  57. /**
  58. * Defines the type of form being created. Set by FormHelper::create().
  59. *
  60. * @var string
  61. */
  62. public $requestType = null;
  63. /**
  64. * The default model being used for the current form.
  65. *
  66. * @var string
  67. */
  68. public $defaultModel = null;
  69. /**
  70. * Persistent default options used by input(). Set by FormHelper::create().
  71. *
  72. * @var array
  73. */
  74. protected $_inputDefaults = array();
  75. /**
  76. * An array of field names that have been excluded from
  77. * the Token hash used by SecurityComponent's validatePost method
  78. *
  79. * @see FormHelper::_secure()
  80. * @see SecurityComponent::validatePost()
  81. * @var array
  82. */
  83. protected $_unlockedFields = array();
  84. /**
  85. * Holds the model references already loaded by this helper
  86. * product of trying to inspect them out of field names
  87. *
  88. * @var array
  89. */
  90. protected $_models = array();
  91. /**
  92. * Holds all the validation errors for models loaded and inspected
  93. * it can also be set manually to be able to display custom error messages
  94. * in the any of the input fields generated by this helper
  95. *
  96. * @var array
  97. */
  98. public $validationErrors = array();
  99. /**
  100. * Copies the validationErrors variable from the View object into this instance
  101. *
  102. * @param View $View The View this helper is being attached to.
  103. * @param array $settings Configuration settings for the helper.
  104. */
  105. public function __construct(View $View, $settings = array()) {
  106. parent::__construct($View, $settings);
  107. $this->validationErrors =& $View->validationErrors;
  108. }
  109. /**
  110. * Guess the location for a model based on its name and tries to create a new instance
  111. * or get an already created instance of the model
  112. *
  113. * @param string $model
  114. * @return Model model instance
  115. */
  116. protected function _getModel($model) {
  117. $object = null;
  118. if (!$model || $model === 'Model') {
  119. return $object;
  120. }
  121. if (array_key_exists($model, $this->_models)) {
  122. return $this->_models[$model];
  123. }
  124. if (ClassRegistry::isKeySet($model)) {
  125. $object = ClassRegistry::getObject($model);
  126. } elseif (isset($this->request->params['models'][$model])) {
  127. $plugin = $this->request->params['models'][$model]['plugin'];
  128. $plugin .= ($plugin) ? '.' : null;
  129. $object = ClassRegistry::init(array(
  130. 'class' => $plugin . $this->request->params['models'][$model]['className'],
  131. 'alias' => $model
  132. ));
  133. } elseif (ClassRegistry::isKeySet($this->defaultModel)) {
  134. $defaultObject = ClassRegistry::getObject($this->defaultModel);
  135. if ($defaultObject && in_array($model, array_keys($defaultObject->getAssociated()), true) && isset($defaultObject->{$model})) {
  136. $object = $defaultObject->{$model};
  137. }
  138. } else {
  139. $object = ClassRegistry::init($model, true);
  140. }
  141. $this->_models[$model] = $object;
  142. if (!$object) {
  143. return null;
  144. }
  145. $this->fieldset[$model] = array('fields' => null, 'key' => $object->primaryKey, 'validates' => null);
  146. return $object;
  147. }
  148. /**
  149. * Inspects the model properties to extract information from them.
  150. * Currently it can extract information from the the fields, the primary key and required fields
  151. *
  152. * The $key parameter accepts the following list of values:
  153. *
  154. * - key: Returns the name of the primary key for the model
  155. * - fields: Returns the model schema
  156. * - validates: returns the list of fields that are required
  157. * - errors: returns the list of validation errors
  158. *
  159. * If the $field parameter is passed if will return the information for that sole field.
  160. *
  161. * `$this->_introspectModel('Post', 'fields', 'title');` will return the schema information for title column
  162. *
  163. * @param string $model name of the model to extract information from
  164. * @param string $key name of the special information key to obtain (key, fields, validates, errors)
  165. * @param string $field name of the model field to get information from
  166. * @return mixed information extracted for the special key and field in a model
  167. */
  168. protected function _introspectModel($model, $key, $field = null) {
  169. $object = $this->_getModel($model);
  170. if (!$object) {
  171. return;
  172. }
  173. if ($key === 'key') {
  174. return $this->fieldset[$model]['key'] = $object->primaryKey;
  175. }
  176. if ($key === 'fields') {
  177. if (!isset($this->fieldset[$model]['fields'])) {
  178. $this->fieldset[$model]['fields'] = $object->schema();
  179. foreach ($object->hasAndBelongsToMany as $alias => $assocData) {
  180. $this->fieldset[$object->alias]['fields'][$alias] = array('type' => 'multiple');
  181. }
  182. }
  183. if ($field === null || $field === false) {
  184. return $this->fieldset[$model]['fields'];
  185. } elseif (isset($this->fieldset[$model]['fields'][$field])) {
  186. return $this->fieldset[$model]['fields'][$field];
  187. } else {
  188. return isset($object->hasAndBelongsToMany[$field]) ? array('type' => 'multiple') : null;
  189. }
  190. }
  191. if ($key === 'errors' && !isset($this->validationErrors[$model])) {
  192. $this->validationErrors[$model] =& $object->validationErrors;
  193. return $this->validationErrors[$model];
  194. } elseif ($key === 'errors' && isset($this->validationErrors[$model])) {
  195. return $this->validationErrors[$model];
  196. }
  197. if ($key === 'validates' && !isset($this->fieldset[$model]['validates'])) {
  198. $validates = array();
  199. if (!empty($object->validate)) {
  200. foreach ($object->validator() as $validateField => $validateProperties) {
  201. if ($this->_isRequiredField($validateProperties)) {
  202. $validates[$validateField] = true;
  203. }
  204. }
  205. }
  206. $this->fieldset[$model]['validates'] = $validates;
  207. }
  208. if ($key === 'validates') {
  209. if (empty($field)) {
  210. return $this->fieldset[$model]['validates'];
  211. } else {
  212. return isset($this->fieldset[$model]['validates'][$field]) ?
  213. $this->fieldset[$model]['validates'] : null;
  214. }
  215. }
  216. }
  217. /**
  218. * Returns if a field is required to be filled based on validation properties from the validating object.
  219. *
  220. * @param CakeValidationSet $validationRules
  221. * @return boolean true if field is required to be filled, false otherwise
  222. */
  223. protected function _isRequiredField($validationRules) {
  224. if (empty($validationRules) || count($validationRules) === 0) {
  225. return false;
  226. }
  227. $isUpdate = $this->requestType === 'put';
  228. foreach ($validationRules as $rule) {
  229. $rule->isUpdate($isUpdate);
  230. if ($rule->skip()) {
  231. continue;
  232. }
  233. return !$rule->allowEmpty;
  234. }
  235. return false;
  236. }
  237. /**
  238. * Returns false if given form field described by the current entity has no errors.
  239. * Otherwise it returns the validation message
  240. *
  241. * @return mixed Either false when there are no errors, or an array of error
  242. * strings. An error string could be ''.
  243. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::tagIsInvalid
  244. */
  245. public function tagIsInvalid() {
  246. $entity = $this->entity();
  247. $model = array_shift($entity);
  248. $errors = array();
  249. if (!empty($entity) && isset($this->validationErrors[$model])) {
  250. $errors = $this->validationErrors[$model];
  251. }
  252. if (!empty($entity) && empty($errors)) {
  253. $errors = $this->_introspectModel($model, 'errors');
  254. }
  255. if (empty($errors)) {
  256. return false;
  257. }
  258. $errors = Hash::get($errors, implode('.', $entity));
  259. return $errors === null ? false : $errors;
  260. }
  261. /**
  262. * Returns an HTML FORM element.
  263. *
  264. * ### Options:
  265. *
  266. * - `type` Form method defaults to POST
  267. * - `action` The controller action the form submits to, (optional).
  268. * - `url` The url the form submits to. Can be a string or a url array. If you use 'url'
  269. * you should leave 'action' undefined.
  270. * - `default` Allows for the creation of Ajax forms. Set this to false to prevent the default event handler.
  271. * Will create an onsubmit attribute if it doesn't not exist. If it does, default action suppression
  272. * will be appended.
  273. * - `onsubmit` Used in conjunction with 'default' to create ajax forms.
  274. * - `inputDefaults` set the default $options for FormHelper::input(). Any options that would
  275. * be set when using FormHelper::input() can be set here. Options set with `inputDefaults`
  276. * can be overridden when calling input()
  277. * - `encoding` Set the accept-charset encoding for the form. Defaults to `Configure::read('App.encoding')`
  278. *
  279. * @param mixed $model The model name for which the form is being defined. Should
  280. * include the plugin name for plugin models. e.g. `ContactManager.Contact`.
  281. * If an array is passed and $options argument is empty, the array will be used as options.
  282. * If `false` no model is used.
  283. * @param array $options An array of html attributes and options.
  284. * @return string An formatted opening FORM tag.
  285. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-create
  286. */
  287. public function create($model = null, $options = array()) {
  288. $created = $id = false;
  289. $append = '';
  290. if (is_array($model) && empty($options)) {
  291. $options = $model;
  292. $model = null;
  293. }
  294. if (empty($model) && $model !== false && !empty($this->request->params['models'])) {
  295. $model = key($this->request->params['models']);
  296. } elseif (empty($model) && empty($this->request->params['models'])) {
  297. $model = false;
  298. }
  299. $this->defaultModel = $model;
  300. $key = null;
  301. if ($model !== false) {
  302. list($plugin, $model) = pluginSplit($model, true);
  303. $key = $this->_introspectModel($plugin . $model, 'key');
  304. $this->setEntity($model, true);
  305. }
  306. if ($model !== false && $key) {
  307. $recordExists = (
  308. isset($this->request->data[$model]) &&
  309. !empty($this->request->data[$model][$key]) &&
  310. !is_array($this->request->data[$model][$key])
  311. );
  312. if ($recordExists) {
  313. $created = true;
  314. $id = $this->request->data[$model][$key];
  315. }
  316. }
  317. $options = array_merge(array(
  318. 'type' => ($created && empty($options['action'])) ? 'put' : 'post',
  319. 'action' => null,
  320. 'url' => null,
  321. 'default' => true,
  322. 'encoding' => strtolower(Configure::read('App.encoding')),
  323. 'inputDefaults' => array()),
  324. $options);
  325. $this->inputDefaults($options['inputDefaults']);
  326. unset($options['inputDefaults']);
  327. if (!isset($options['id'])) {
  328. $domId = isset($options['action']) ? $options['action'] : $this->request['action'];
  329. $options['id'] = $this->domId($domId . 'Form');
  330. }
  331. if ($options['action'] === null && $options['url'] === null) {
  332. $options['action'] = $this->request->here(false);
  333. } elseif (empty($options['url']) || is_array($options['url'])) {
  334. if (empty($options['url']['controller'])) {
  335. if (!empty($model)) {
  336. $options['url']['controller'] = Inflector::underscore(Inflector::pluralize($model));
  337. } elseif (!empty($this->request->params['controller'])) {
  338. $options['url']['controller'] = Inflector::underscore($this->request->params['controller']);
  339. }
  340. }
  341. if (empty($options['action'])) {
  342. $options['action'] = $this->request->params['action'];
  343. }
  344. $plugin = null;
  345. if ($this->plugin) {
  346. $plugin = Inflector::underscore($this->plugin);
  347. }
  348. $actionDefaults = array(
  349. 'plugin' => $plugin,
  350. 'controller' => $this->_View->viewPath,
  351. 'action' => $options['action'],
  352. );
  353. $options['action'] = array_merge($actionDefaults, (array)$options['url']);
  354. if (empty($options['action'][0]) && !empty($id)) {
  355. $options['action'][0] = $id;
  356. }
  357. } elseif (is_string($options['url'])) {
  358. $options['action'] = $options['url'];
  359. }
  360. unset($options['url']);
  361. switch (strtolower($options['type'])) {
  362. case 'get':
  363. $htmlAttributes['method'] = 'get';
  364. break;
  365. case 'file':
  366. $htmlAttributes['enctype'] = 'multipart/form-data';
  367. $options['type'] = ($created) ? 'put' : 'post';
  368. case 'post':
  369. case 'put':
  370. case 'delete':
  371. $append .= $this->hidden('_method', array(
  372. 'name' => '_method', 'value' => strtoupper($options['type']), 'id' => null,
  373. 'secure' => self::SECURE_SKIP
  374. ));
  375. default:
  376. $htmlAttributes['method'] = 'post';
  377. break;
  378. }
  379. $this->requestType = strtolower($options['type']);
  380. $action = $this->url($options['action']);
  381. unset($options['type'], $options['action']);
  382. if (!$options['default']) {
  383. if (!isset($options['onsubmit'])) {
  384. $options['onsubmit'] = '';
  385. }
  386. $htmlAttributes['onsubmit'] = $options['onsubmit'] . 'event.returnValue = false; return false;';
  387. }
  388. unset($options['default']);
  389. if (!empty($options['encoding'])) {
  390. $htmlAttributes['accept-charset'] = $options['encoding'];
  391. unset($options['encoding']);
  392. }
  393. $htmlAttributes = array_merge($options, $htmlAttributes);
  394. $this->fields = array();
  395. if ($this->requestType !== 'get') {
  396. $append .= $this->_csrfField();
  397. }
  398. if (!empty($append)) {
  399. $append = $this->Html->useTag('hiddenblock', $append);
  400. }
  401. if ($model !== false) {
  402. $this->setEntity($model, true);
  403. $this->_introspectModel($model, 'fields');
  404. }
  405. return $this->Html->useTag('form', $action, $htmlAttributes) . $append;
  406. }
  407. /**
  408. * Return a CSRF input if the _Token is present.
  409. * Used to secure forms in conjunction with SecurityComponent
  410. *
  411. * @return string
  412. */
  413. protected function _csrfField() {
  414. if (empty($this->request->params['_Token'])) {
  415. return '';
  416. }
  417. if (!empty($this->request['_Token']['unlockedFields'])) {
  418. foreach ((array)$this->request['_Token']['unlockedFields'] as $unlocked) {
  419. $this->_unlockedFields[] = $unlocked;
  420. }
  421. }
  422. return $this->hidden('_Token.key', array(
  423. 'value' => $this->request->params['_Token']['key'], 'id' => 'Token' . mt_rand(),
  424. 'secure' => self::SECURE_SKIP
  425. ));
  426. }
  427. /**
  428. * Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden
  429. * input fields where appropriate.
  430. *
  431. * If $options is set a form submit button will be created. Options can be either a string or an array.
  432. *
  433. * {{{
  434. * array usage:
  435. *
  436. * array('label' => 'save'); value="save"
  437. * array('label' => 'save', 'name' => 'Whatever'); value="save" name="Whatever"
  438. * array('name' => 'Whatever'); value="Submit" name="Whatever"
  439. * array('label' => 'save', 'name' => 'Whatever', 'div' => 'good') <div class="good"> value="save" name="Whatever"
  440. * array('label' => 'save', 'name' => 'Whatever', 'div' => array('class' => 'good')); <div class="good"> value="save" name="Whatever"
  441. * }}}
  442. *
  443. * @param string|array $options as a string will use $options as the value of button,
  444. * @return string a closing FORM tag optional submit button.
  445. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#closing-the-form
  446. */
  447. public function end($options = null) {
  448. $out = null;
  449. $submit = null;
  450. if ($options !== null) {
  451. $submitOptions = array();
  452. if (is_string($options)) {
  453. $submit = $options;
  454. } else {
  455. if (isset($options['label'])) {
  456. $submit = $options['label'];
  457. unset($options['label']);
  458. }
  459. $submitOptions = $options;
  460. }
  461. $out .= $this->submit($submit, $submitOptions);
  462. }
  463. if (
  464. $this->requestType !== 'get' &&
  465. isset($this->request['_Token']) &&
  466. !empty($this->request['_Token'])
  467. ) {
  468. $out .= $this->secure($this->fields);
  469. $this->fields = array();
  470. }
  471. $this->setEntity(null);
  472. $out .= $this->Html->useTag('formend');
  473. $this->_View->modelScope = false;
  474. return $out;
  475. }
  476. /**
  477. * Generates a hidden field with a security hash based on the fields used in the form.
  478. *
  479. * @param array $fields The list of fields to use when generating the hash
  480. * @return string A hidden input field with a security hash
  481. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::secure
  482. */
  483. public function secure($fields = array()) {
  484. if (!isset($this->request['_Token']) || empty($this->request['_Token'])) {
  485. return;
  486. }
  487. $locked = array();
  488. $unlockedFields = $this->_unlockedFields;
  489. foreach ($fields as $key => $value) {
  490. if (!is_int($key)) {
  491. $locked[$key] = $value;
  492. unset($fields[$key]);
  493. }
  494. }
  495. sort($unlockedFields, SORT_STRING);
  496. sort($fields, SORT_STRING);
  497. ksort($locked, SORT_STRING);
  498. $fields += $locked;
  499. $locked = implode(array_keys($locked), '|');
  500. $unlocked = implode($unlockedFields, '|');
  501. $fields = Security::hash(serialize($fields) . $unlocked . Configure::read('Security.salt'), 'sha1');
  502. $out = $this->hidden('_Token.fields', array(
  503. 'value' => urlencode($fields . ':' . $locked),
  504. 'id' => 'TokenFields' . mt_rand()
  505. ));
  506. $out .= $this->hidden('_Token.unlocked', array(
  507. 'value' => urlencode($unlocked),
  508. 'id' => 'TokenUnlocked' . mt_rand()
  509. ));
  510. return $this->Html->useTag('hiddenblock', $out);
  511. }
  512. /**
  513. * Add to or get the list of fields that are currently unlocked.
  514. * Unlocked fields are not included in the field hash used by SecurityComponent
  515. * unlocking a field once its been added to the list of secured fields will remove
  516. * it from the list of fields.
  517. *
  518. * @param string $name The dot separated name for the field.
  519. * @return mixed Either null, or the list of fields.
  520. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::unlockField
  521. */
  522. public function unlockField($name = null) {
  523. if ($name === null) {
  524. return $this->_unlockedFields;
  525. }
  526. if (!in_array($name, $this->_unlockedFields)) {
  527. $this->_unlockedFields[] = $name;
  528. }
  529. $index = array_search($name, $this->fields);
  530. if ($index !== false) {
  531. unset($this->fields[$index]);
  532. }
  533. unset($this->fields[$name]);
  534. }
  535. /**
  536. * Determine which fields of a form should be used for hash.
  537. * Populates $this->fields
  538. *
  539. * @param boolean $lock Whether this field should be part of the validation
  540. * or excluded as part of the unlockedFields.
  541. * @param string|array $field Reference to field to be secured. Should be dot separated to indicate nesting.
  542. * @param mixed $value Field value, if value should not be tampered with.
  543. * @return void
  544. */
  545. protected function _secure($lock, $field = null, $value = null) {
  546. if (!$field) {
  547. $field = $this->entity();
  548. } elseif (is_string($field)) {
  549. $field = Hash::filter(explode('.', $field));
  550. }
  551. foreach ($this->_unlockedFields as $unlockField) {
  552. $unlockParts = explode('.', $unlockField);
  553. if (array_values(array_intersect($field, $unlockParts)) === $unlockParts) {
  554. return;
  555. }
  556. }
  557. $field = implode('.', $field);
  558. $field = preg_replace('/(\.\d+)+$/', '', $field);
  559. if ($lock) {
  560. if (!in_array($field, $this->fields)) {
  561. if ($value !== null) {
  562. return $this->fields[$field] = $value;
  563. }
  564. $this->fields[] = $field;
  565. }
  566. } else {
  567. $this->unlockField($field);
  568. }
  569. }
  570. /**
  571. * Returns true if there is an error for the given field, otherwise false
  572. *
  573. * @param string $field This should be "Modelname.fieldname"
  574. * @return boolean If there are errors this method returns true, else false.
  575. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::isFieldError
  576. */
  577. public function isFieldError($field) {
  578. $this->setEntity($field);
  579. return (bool)$this->tagIsInvalid();
  580. }
  581. /**
  582. * Returns a formatted error message for given FORM field, NULL if no errors.
  583. *
  584. * ### Options:
  585. *
  586. * - `escape` bool Whether or not to html escape the contents of the error.
  587. * - `wrap` mixed Whether or not the error message should be wrapped in a div. If a
  588. * string, will be used as the HTML tag to use.
  589. * - `class` string The classname for the error message
  590. *
  591. * @param string $field A field name, like "Modelname.fieldname"
  592. * @param string|array $text Error message as string or array of messages.
  593. * If array contains `attributes` key it will be used as options for error container
  594. * @param array $options Rendering options for <div /> wrapper tag
  595. * @return string If there are errors this method returns an error message, otherwise null.
  596. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::error
  597. */
  598. public function error($field, $text = null, $options = array()) {
  599. $defaults = array('wrap' => true, 'class' => 'error-message', 'escape' => true);
  600. $options = array_merge($defaults, $options);
  601. $this->setEntity($field);
  602. $error = $this->tagIsInvalid();
  603. if ($error === false) {
  604. return null;
  605. }
  606. if (is_array($text)) {
  607. if (isset($text['attributes']) && is_array($text['attributes'])) {
  608. $options = array_merge($options, $text['attributes']);
  609. unset($text['attributes']);
  610. }
  611. $tmp = array();
  612. foreach ($error as &$e) {
  613. if (isset($text[$e])) {
  614. $tmp[] = $text[$e];
  615. } else {
  616. $tmp[] = $e;
  617. }
  618. }
  619. $text = $tmp;
  620. }
  621. if ($text !== null) {
  622. $error = $text;
  623. }
  624. if (is_array($error)) {
  625. foreach ($error as &$e) {
  626. if (is_numeric($e)) {
  627. $e = __d('cake', 'Error in field %s', Inflector::humanize($this->field()));
  628. }
  629. }
  630. }
  631. if ($options['escape']) {
  632. $error = h($error);
  633. unset($options['escape']);
  634. }
  635. if (is_array($error)) {
  636. if (count($error) > 1) {
  637. $listParams = array();
  638. if (isset($options['listOptions'])) {
  639. if (is_string($options['listOptions'])) {
  640. $listParams[] = $options['listOptions'];
  641. } else {
  642. if (isset($options['listOptions']['itemOptions'])) {
  643. $listParams[] = $options['listOptions']['itemOptions'];
  644. unset($options['listOptions']['itemOptions']);
  645. } else {
  646. $listParams[] = array();
  647. }
  648. if (isset($options['listOptions']['tag'])) {
  649. $listParams[] = $options['listOptions']['tag'];
  650. unset($options['listOptions']['tag']);
  651. }
  652. array_unshift($listParams, $options['listOptions']);
  653. }
  654. unset($options['listOptions']);
  655. }
  656. array_unshift($listParams, $error);
  657. $error = call_user_func_array(array($this->Html, 'nestedList'), $listParams);
  658. } else {
  659. $error = array_pop($error);
  660. }
  661. }
  662. if ($options['wrap']) {
  663. $tag = is_string($options['wrap']) ? $options['wrap'] : 'div';
  664. unset($options['wrap']);
  665. return $this->Html->tag($tag, $error, $options);
  666. } else {
  667. return $error;
  668. }
  669. }
  670. /**
  671. * Returns a formatted LABEL element for HTML FORMs. Will automatically generate
  672. * a `for` attribute if one is not provided.
  673. *
  674. * ### Options
  675. *
  676. * - `for` - Set the for attribute, if its not defined the for attribute
  677. * will be generated from the $fieldName parameter using
  678. * FormHelper::domId().
  679. *
  680. * Examples:
  681. *
  682. * The text and for attribute are generated off of the fieldname
  683. *
  684. * {{{
  685. * echo $this->Form->label('Post.published');
  686. * <label for="PostPublished">Published</label>
  687. * }}}
  688. *
  689. * Custom text:
  690. *
  691. * {{{
  692. * echo $this->Form->label('Post.published', 'Publish');
  693. * <label for="PostPublished">Publish</label>
  694. * }}}
  695. *
  696. * Custom class name:
  697. *
  698. * {{{
  699. * echo $this->Form->label('Post.published', 'Publish', 'required');
  700. * <label for="PostPublished" class="required">Publish</label>
  701. * }}}
  702. *
  703. * Custom attributes:
  704. *
  705. * {{{
  706. * echo $this->Form->label('Post.published', 'Publish', array(
  707. * 'for' => 'post-publish'
  708. * ));
  709. * <label for="post-publish">Publish</label>
  710. * }}}
  711. *
  712. * @param string $fieldName This should be "Modelname.fieldname"
  713. * @param string $text Text that will appear in the label field. If
  714. * $text is left undefined the text will be inflected from the
  715. * fieldName.
  716. * @param array|string $options An array of HTML attributes, or a string, to be used as a class name.
  717. * @return string The formatted LABEL element
  718. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::label
  719. */
  720. public function label($fieldName = null, $text = null, $options = array()) {
  721. if ($fieldName === null) {
  722. $fieldName = implode('.', $this->entity());
  723. }
  724. if ($text === null) {
  725. if (strpos($fieldName, '.') !== false) {
  726. $fieldElements = explode('.', $fieldName);
  727. $text = array_pop($fieldElements);
  728. } else {
  729. $text = $fieldName;
  730. }
  731. if (substr($text, -3) === '_id') {
  732. $text = substr($text, 0, -3);
  733. }
  734. $text = __(Inflector::humanize(Inflector::underscore($text)));
  735. }
  736. if (is_string($options)) {
  737. $options = array('class' => $options);
  738. }
  739. if (isset($options['for'])) {
  740. $labelFor = $options['for'];
  741. unset($options['for']);
  742. } else {
  743. $labelFor = $this->domId($fieldName);
  744. }
  745. return $this->Html->useTag('label', $labelFor, $options, $text);
  746. }
  747. /**
  748. * Generate a set of inputs for `$fields`. If $fields is null the fields of current model
  749. * will be used.
  750. *
  751. * You can customize individual inputs through `$fields`.
  752. * {{{
  753. * $this->Form->inputs(array(
  754. * 'name' => array('label' => 'custom label')
  755. * ));
  756. * }}}
  757. *
  758. * In addition to controller fields output, `$fields` can be used to control legend
  759. * and fieldset rendering.
  760. * `$this->Form->inputs('My legend');` Would generate an input set with a custom legend.
  761. * Passing `fieldset` and `legend` key in `$fields` array has been deprecated since 2.3,
  762. * for more fine grained control use the `fieldset` and `legend` keys in `$options` param.
  763. *
  764. * @param array $fields An array of fields to generate inputs for, or null.
  765. * @param array $blacklist A simple array of fields to not create inputs for.
  766. * @param array $options Options array. Valid keys are:
  767. * - `fieldset` Set to false to disable the fieldset. If a string is supplied it will be used as
  768. * the classname for the fieldset element.
  769. * - `legend` Set to false to disable the legend for the generated input set. Or supply a string
  770. * to customize the legend text.
  771. * @return string Completed form inputs.
  772. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::inputs
  773. */
  774. public function inputs($fields = null, $blacklist = null, $options = array()) {
  775. $fieldset = $legend = true;
  776. $modelFields = array();
  777. $model = $this->model();
  778. if ($model) {
  779. $modelFields = array_keys((array)$this->_introspectModel($model, 'fields'));
  780. }
  781. if (is_array($fields)) {
  782. if (array_key_exists('legend', $fields) && !in_array('legend', $modelFields)) {
  783. $legend = $fields['legend'];
  784. unset($fields['legend']);
  785. }
  786. if (isset($fields['fieldset']) && !in_array('fieldset', $modelFields)) {
  787. $fieldset = $fields['fieldset'];
  788. unset($fields['fieldset']);
  789. }
  790. } elseif ($fields !== null) {
  791. $fieldset = $legend = $fields;
  792. if (!is_bool($fieldset)) {
  793. $fieldset = true;
  794. }
  795. $fields = array();
  796. }
  797. if (isset($options['legend'])) {
  798. $legend = $options['legend'];
  799. }
  800. if (isset($options['fieldset'])) {
  801. $fieldset = $options['fieldset'];
  802. }
  803. if (empty($fields)) {
  804. $fields = $modelFields;
  805. }
  806. if ($legend === true) {
  807. $actionName = __d('cake', 'New %s');
  808. $isEdit = (
  809. strpos($this->request->params['action'], 'update') !== false ||
  810. strpos($this->request->params['action'], 'edit') !== false
  811. );
  812. if ($isEdit) {
  813. $actionName = __d('cake', 'Edit %s');
  814. }
  815. $modelName = Inflector::humanize(Inflector::underscore($model));
  816. $legend = sprintf($actionName, __($modelName));
  817. }
  818. $out = null;
  819. foreach ($fields as $name => $options) {
  820. if (is_numeric($name) && !is_array($options)) {
  821. $name = $options;
  822. $options = array();
  823. }
  824. $entity = explode('.', $name);
  825. $blacklisted = (
  826. is_array($blacklist) &&
  827. (in_array($name, $blacklist) || in_array(end($entity), $blacklist))
  828. );
  829. if ($blacklisted) {
  830. continue;
  831. }
  832. $out .= $this->input($name, $options);
  833. }
  834. if (is_string($fieldset)) {
  835. $fieldsetClass = sprintf(' class="%s"', $fieldset);
  836. } else {
  837. $fieldsetClass = '';
  838. }
  839. if ($fieldset) {
  840. if ($legend) {
  841. $out = $this->Html->useTag('legend', $legend) . $out;
  842. }
  843. $out = $this->Html->useTag('fieldset', $fieldsetClass, $out);
  844. }
  845. return $out;
  846. }
  847. /**
  848. * Generates a form input element complete with label and wrapper div
  849. *
  850. * ### Options
  851. *
  852. * See each field type method for more information. Any options that are part of
  853. * $attributes or $options for the different **type** methods can be included in `$options` for input().i
  854. * Additionally, any unknown keys that are not in the list below, or part of the selected type's options
  855. * will be treated as a regular html attribute for the generated input.
  856. *
  857. * - `type` - Force the type of widget you want. e.g. `type => 'select'`
  858. * - `label` - Either a string label, or an array of options for the label. See FormHelper::label().
  859. * - `div` - Either `false` to disable the div, or an array of options for the div.
  860. * See HtmlHelper::div() for more options.
  861. * - `options` - For widgets that take options e.g. radio, select.
  862. * - `error` - Control the error message that is produced. Set to `false` to disable any kind of error reporting (field
  863. * error and error messages).
  864. * - `errorMessage` - Boolean to control rendering error messages (field error will still occur).
  865. * - `empty` - String or boolean to enable empty select box options.
  866. * - `before` - Content to place before the label + input.
  867. * - `after` - Content to place after the label + input.
  868. * - `between` - Content to place between the label + input.
  869. * - `format` - Format template for element order. Any element that is not in the array, will not be in the output.
  870. * - Default input format order: array('before', 'label', 'between', 'input', 'after', 'error')
  871. * - Default checkbox format order: array('before', 'input', 'between', 'label', 'after', 'error')
  872. * - Hidden input will not be formatted
  873. * - Radio buttons cannot have the order of input and label elements controlled with these settings.
  874. *
  875. * @param string $fieldName This should be "Modelname.fieldname"
  876. * @param array $options Each type of input takes different options.
  877. * @return string Completed form widget.
  878. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#creating-form-elements
  879. */
  880. public function input($fieldName, $options = array()) {
  881. $this->setEntity($fieldName);
  882. $options = $this->_parseOptions($options);
  883. $divOptions = $this->_divOptions($options);
  884. unset($options['div']);
  885. if ($options['type'] === 'radio' && isset($options['options'])) {
  886. $radioOptions = (array)$options['options'];
  887. unset($options['options']);
  888. }
  889. $label = $this->_getLabel($fieldName, $options);
  890. if ($options['type'] !== 'radio') {
  891. unset($options['label']);
  892. }
  893. $error = $this->_extractOption('error', $options, null);
  894. unset($options['error']);
  895. $errorMessage = $this->_extractOption('errorMessage', $options, true);
  896. unset($options['errorMessage']);
  897. $selected = $this->_extractOption('selected', $options, null);
  898. unset($options['selected']);
  899. if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time') {
  900. $dateFormat = $this->_extractOption('dateFormat', $options, 'MDY');
  901. $timeFormat = $this->_extractOption('timeFormat', $options, 12);
  902. unset($options['dateFormat'], $options['timeFormat']);
  903. }
  904. $type = $options['type'];
  905. $out = array('before' => $options['before'], 'label' => $label, 'between' => $options['between'], 'after' => $options['after']);
  906. $format = $this->_getFormat($options);
  907. unset($options['type'], $options['before'], $options['between'], $options['after'], $options['format']);
  908. $out['error'] = null;
  909. if ($type !== 'hidden' && $error !== false) {
  910. $errMsg = $this->error($fieldName, $error);
  911. if ($errMsg) {
  912. $divOptions = $this->addClass($divOptions, 'error');
  913. if ($errorMessage) {
  914. $out['error'] = $errMsg;
  915. }
  916. }
  917. }
  918. if ($type === 'radio' && isset($out['between'])) {
  919. $options['between'] = $out['between'];
  920. $out['between'] = null;
  921. }
  922. $out['input'] = $this->_getInput(compact('type', 'fieldName', 'options', 'radioOptions', 'selected', 'dateFormat', 'timeFormat'));
  923. $output = '';
  924. foreach ($format as $element) {
  925. $output .= $out[$element];
  926. }
  927. if (!empty($divOptions['tag'])) {
  928. $tag = $divOptions['tag'];
  929. unset($divOptions['tag']);
  930. $output = $this->Html->tag($tag, $output, $divOptions);
  931. }
  932. return $output;
  933. }
  934. /**
  935. * Generates an input element
  936. *
  937. * @param type $args
  938. * @return type
  939. */
  940. protected function _getInput($args) {
  941. extract($args);
  942. switch ($type) {
  943. case 'hidden':
  944. return $this->hidden($fieldName, $options);
  945. case 'checkbox':
  946. return $this->checkbox($fieldName, $options);
  947. case 'radio':
  948. return $this->radio($fieldName, $radioOptions, $options);
  949. case 'file':
  950. return $this->file($fieldName, $options);
  951. case 'select':
  952. $options += array('options' => array(), 'value' => $selected);
  953. $list = $options['options'];
  954. unset($options['options']);
  955. return $this->select($fieldName, $list, $options);
  956. case 'time':
  957. $options['value'] = $selected;
  958. return $this->dateTime($fieldName, null, $timeFormat, $options);
  959. case 'date':
  960. $options['value'] = $selected;
  961. return $this->dateTime($fieldName, $dateFormat, null, $options);
  962. case 'datetime':
  963. $options['value'] = $selected;
  964. return $this->dateTime($fieldName, $dateFormat, $timeFormat, $options);
  965. case 'textarea':
  966. return $this->textarea($fieldName, $options + array('cols' => '30', 'rows' => '6'));
  967. case 'url':
  968. return $this->text($fieldName, array('type' => 'url') + $options);
  969. default:
  970. return $this->{$type}($fieldName, $options);
  971. }
  972. }
  973. /**
  974. * Generates input options array
  975. *
  976. * @param type $options
  977. * @return array Options
  978. */
  979. protected function _parseOptions($options) {
  980. $options = array_merge(
  981. array('before' => null, 'between' => null, 'after' => null, 'format' => null),
  982. $this->_inputDefaults,
  983. $options
  984. );
  985. if (!isset($options['type'])) {
  986. $options = $this->_magicOptions($options);
  987. }
  988. if (in_array($options['type'], array('checkbox', 'radio', 'select'))) {
  989. $options = $this->_optionsOptions($options);
  990. }
  991. if (isset($options['rows']) || isset($options['cols'])) {
  992. $options['type'] = 'textarea';
  993. }
  994. if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time' || $options['type'] === 'select') {
  995. $options += array('empty' => false);
  996. }
  997. return $options;
  998. }
  999. /**
  1000. * Generates list of options for multiple select
  1001. *
  1002. * @param type $options
  1003. * @return array
  1004. */
  1005. protected function _optionsOptions($options) {
  1006. if (isset($options['options'])) {
  1007. return $options;
  1008. }
  1009. $varName = Inflector::variable(
  1010. Inflector::pluralize(preg_replace('/_id$/', '', $this->field()))
  1011. );
  1012. $varOptions = $this->_View->getVar($varName);
  1013. if (!is_array($varOptions)) {
  1014. return $options;
  1015. }
  1016. if ($options['type'] !== 'radio') {
  1017. $options['type'] = 'select';
  1018. }
  1019. $options['options'] = $varOptions;
  1020. return $options;
  1021. }
  1022. /**
  1023. * Magically set option type and corresponding options
  1024. *
  1025. * @param type $options
  1026. * @return array
  1027. */
  1028. protected function _magicOptions($options) {
  1029. $modelKey = $this->model();
  1030. $fieldKey = $this->field();
  1031. $options['type'] = 'text';
  1032. if (isset($options['options'])) {
  1033. $options['type'] = 'select';
  1034. } elseif (in_array($fieldKey, array('psword', 'passwd', 'password'))) {
  1035. $options['type'] = 'password';
  1036. } elseif (in_array($fieldKey, array('tel', 'telephone', 'phone'))) {
  1037. $options['type'] = 'tel';
  1038. } elseif ($fieldKey === 'email') {
  1039. $options['type'] = 'email';
  1040. } elseif (isset($options['checked'])) {
  1041. $options['type'] = 'checkbox';
  1042. } elseif ($fieldDef = $this->_introspectModel($modelKey, 'fields', $fieldKey)) {
  1043. $type = $fieldDef['type'];
  1044. $primaryKey = $this->fieldset[$modelKey]['key'];
  1045. $map = array(
  1046. 'string' => 'text', 'datetime' => 'datetime',
  1047. 'boolean' => 'checkbox', 'timestamp' => 'datetime',
  1048. 'text' => 'textarea', 'time' => 'time',
  1049. 'date' => 'date', 'float' => 'number',
  1050. 'integer' => 'number'
  1051. );
  1052. if (isset($this->map[$type])) {
  1053. $options['type'] = $this->map[$type];
  1054. } elseif (isset($map[$type])) {
  1055. $options['type'] = $map[$type];
  1056. }
  1057. if ($fieldKey == $primaryKey) {
  1058. $options['type'] = 'hidden';
  1059. }
  1060. if (
  1061. $options['type'] === 'number' &&
  1062. $type === 'float' &&
  1063. !isset($options['step'])
  1064. ) {
  1065. $options['step'] = 'any';
  1066. }
  1067. }
  1068. if (preg_match('/_id$/', $fieldKey) && $options['type'] !== 'hidden') {
  1069. $options['type'] = 'select';
  1070. }
  1071. if ($modelKey === $fieldKey) {
  1072. $options['type'] = 'select';
  1073. if (!isset($options['multiple'])) {
  1074. $options['multiple'] = 'multiple';
  1075. }
  1076. }
  1077. if (in_array($options['type'], array('text', 'number'))) {
  1078. $options = $this->_optionsOptions($options);
  1079. }
  1080. if ($options['type'] === 'select' && array_key_exists('step', $options)) {
  1081. unset($options['step']);
  1082. }
  1083. $options = $this->_maxLength($options);
  1084. return $options;
  1085. }
  1086. /**
  1087. * Generate format options
  1088. *
  1089. * @param type $options
  1090. * @return array
  1091. */
  1092. protected function _getFormat($options) {
  1093. if ($options['type'] === 'hidden') {
  1094. return array('input');
  1095. }
  1096. if (is_array($options['format']) && in_array('input', $options['format'])) {
  1097. return $options['format'];
  1098. }
  1099. if ($options['type'] === 'checkbox') {
  1100. return array('before', 'input', 'between', 'label', 'after', 'error');
  1101. }
  1102. return array('before', 'label', 'between', 'input', 'after', 'error');
  1103. }
  1104. /**
  1105. * Generate label for input
  1106. *
  1107. * @param type $fieldName
  1108. * @param type $options
  1109. * @return boolean|string false or Generated label element
  1110. */
  1111. protected function _getLabel($fieldName, $options) {
  1112. if ($options['type'] === 'radio') {
  1113. return false;
  1114. }
  1115. $label = null;
  1116. if (isset($options['label'])) {
  1117. $label = $options['label'];
  1118. }
  1119. if ($label === false) {
  1120. return false;
  1121. }
  1122. return $this->_inputLabel($fieldName, $label, $options);
  1123. }
  1124. /**
  1125. * Calculates maxlength option
  1126. *
  1127. * @param type $options
  1128. * @return array
  1129. */
  1130. protected function _maxLength($options) {
  1131. $fieldDef = $this->_introspectModel($this->model(), 'fields', $this->field());
  1132. $autoLength = (
  1133. !array_key_exists('maxlength', $options) &&
  1134. isset($fieldDef['length']) &&
  1135. is_scalar($fieldDef['length']) &&
  1136. $options['type'] !== 'select'
  1137. );
  1138. if ($autoLength &&
  1139. in_array($options['type'], array('text', 'email', 'tel', 'url', 'search'))
  1140. ) {
  1141. $options['maxlength'] = $fieldDef['length'];
  1142. }
  1143. return $options;
  1144. }
  1145. /**
  1146. * Generate div options for input
  1147. *
  1148. * @param array $options
  1149. * @return array
  1150. */
  1151. protected function _divOptions($options) {
  1152. if ($options['type'] === 'hidden') {
  1153. return array();
  1154. }
  1155. $div = $this->_extractOption('div', $options, true);
  1156. if (!$div) {
  1157. return array();
  1158. }
  1159. $divOptions = array('class' => 'input');
  1160. $divOptions = $this->addClass($divOptions, $options['type']);
  1161. if (is_string($div)) {
  1162. $divOptions['class'] = $div;
  1163. } elseif (is_array($div)) {
  1164. $divOptions = array_merge($divOptions, $div);
  1165. }
  1166. if ($this->_introspectModel($this->model(), 'validates', $this->field())) {
  1167. $divOptions = $this->addClass($divOptions, 'required');
  1168. }
  1169. if (!isset($divOptions['tag'])) {
  1170. $divOptions['tag'] = 'div';
  1171. }
  1172. return $divOptions;
  1173. }
  1174. /**
  1175. * Extracts a single option from an options array.
  1176. *
  1177. * @param string $name The name of the option to pull out.
  1178. * @param array $options The array of options you want to extract.
  1179. * @param mixed $default The default option value
  1180. * @return mixed the contents of the option or default
  1181. */
  1182. protected function _extractOption($name, $options, $default = null) {
  1183. if (array_key_exists($name, $options)) {
  1184. return $options[$name];
  1185. }
  1186. return $default;
  1187. }
  1188. /**
  1189. * Generate a label for an input() call.
  1190. *
  1191. * $options can contain a hash of id overrides. These overrides will be
  1192. * used instead of the generated values if present.
  1193. *
  1194. * @param string $fieldName
  1195. * @param string $label
  1196. * @param array $options Options for the label element.
  1197. * @return string Generated label element
  1198. * @deprecated 'NONE' option is deprecated and will be removed in 3.0
  1199. */
  1200. protected function _inputLabel($fieldName, $label, $options) {
  1201. $labelAttributes = $this->domId(array(), 'for');
  1202. $idKey = null;
  1203. if ($options['type'] === 'date' || $options['type'] === 'datetime') {
  1204. $firstInput = 'M';
  1205. if (
  1206. array_key_exists('dateFormat', $options) &&
  1207. ($options['dateFormat'] === null || $options['dateFormat'] === 'NONE')
  1208. ) {
  1209. $firstInput = 'H';
  1210. } elseif (!empty($options['dateFormat'])) {
  1211. $firstInput = substr($options['dateFormat'], 0, 1);
  1212. }
  1213. switch ($firstInput) {
  1214. case 'D':
  1215. $idKey = 'day';
  1216. $labelAttributes['for'] .= 'Day';
  1217. break;
  1218. case 'Y':
  1219. $idKey = 'year';
  1220. $labelAttributes['for'] .= 'Year';
  1221. break;
  1222. case 'M':
  1223. $idKey = 'month';
  1224. $labelAttributes['for'] .= 'Month';
  1225. break;
  1226. case 'H':
  1227. $idKey = 'hour';
  1228. $labelAttributes['for'] .= 'Hour';
  1229. }
  1230. }
  1231. if ($options['type'] === 'time') {
  1232. $labelAttributes['for'] .= 'Hour';
  1233. $idKey = 'hour';
  1234. }
  1235. if (isset($idKey) && isset($options['id']) && isset($options['id'][$idKey])) {
  1236. $labelAttributes['for'] = $options['id'][$idKey];
  1237. }
  1238. if (is_array($label)) {
  1239. $labelText = null;
  1240. if (isset($label['text'])) {
  1241. $labelText = $label['text'];
  1242. unset($label['text']);
  1243. }
  1244. $labelAttributes = array_merge($labelAttributes, $label);
  1245. } else {
  1246. $labelText = $label;
  1247. }
  1248. if (isset($options['id']) && is_string($options['id'])) {
  1249. $labelAttributes = array_merge($labelAttributes, array('for' => $options['id']));
  1250. }
  1251. return $this->label($fieldName, $labelText, $labelAttributes);
  1252. }
  1253. /**
  1254. * Creates a checkbox input widget.
  1255. *
  1256. * ### Options:
  1257. *
  1258. * - `value` - the value of the checkbox
  1259. * - `checked` - boolean indicate that this checkbox is checked.
  1260. * - `hiddenField` - boolean to indicate if you want the results of checkbox() to include
  1261. * a hidden input with a value of ''.
  1262. * - `disabled` - create a disabled input.
  1263. * - `default` - Set the default value for the checkbox. This allows you to start checkboxes
  1264. * as checked, without having to check the POST data. A matching POST data value, will overwrite
  1265. * the default value.
  1266. *
  1267. * @param string $fieldName Name of a field, like this "Modelname.fieldname"
  1268. * @param array $options Array of HTML attributes.
  1269. * @return string An HTML text input element.
  1270. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
  1271. */
  1272. public function checkbox($fieldName, $options = array()) {
  1273. $valueOptions = array();
  1274. if (isset($options['default'])) {
  1275. $valueOptions['default'] = $options['default'];
  1276. unset($options['default']);
  1277. }
  1278. $options += array('required' => false);
  1279. $options = $this->_initInputField($fieldName, $options) + array('hiddenField' => true);
  1280. $value = current($this->value($valueOptions));
  1281. $output = '';
  1282. if (empty($options['value'])) {
  1283. $options['value'] = 1;
  1284. }
  1285. if (
  1286. (!isset($options['checked']) && !empty($value) && $value == $options['value']) ||
  1287. !empty($options['checked'])
  1288. ) {
  1289. $options['checked'] = 'checked';
  1290. }
  1291. if ($options['hiddenField']) {
  1292. $hiddenOptions = array(
  1293. 'id' => $options['id'] . '_',
  1294. 'name' => $options['name'],
  1295. 'value' => ($options['hiddenField'] !== true ? $options['hiddenField'] : '0'),
  1296. 'secure' => false
  1297. );
  1298. if (isset($options['disabled']) && $options['disabled']) {
  1299. $hiddenOptions['disabled'] = 'disabled';
  1300. }
  1301. $output = $this->hidden($fieldName, $hiddenOptions);
  1302. }
  1303. unset($options['hiddenField']);
  1304. return $output . $this->Html->useTag('checkbox', $options['name'], array_diff_key($options, array('name' => null)));
  1305. }
  1306. /**
  1307. * Creates a set of radio widgets. Will create a legend and fieldset
  1308. * by default. Use $options to control this
  1309. *
  1310. * ### Attributes:
  1311. *
  1312. * - `separator` - define the string in between the radio buttons
  1313. * - `between` - the string between legend and input set or array of strings to insert
  1314. * strings between each input block
  1315. * - `legend` - control whether or not the widget set has a fieldset & legend
  1316. * - `value` - indicate a value that is should be checked
  1317. * - `label` - boolean to indicate whether or not labels for widgets show be displayed
  1318. * - `hiddenField` - boolean to indicate if you want the results of radio() to include
  1319. * a hidden input with a value of ''. This is useful for creating radio sets that non-continuous
  1320. * - `disabled` - Set to `true` or `disabled` to disable all the radio buttons.
  1321. * - `empty` - Set to `true` to create a input with the value '' as the first option. When `true`
  1322. * the radio label will be 'empty'. Set this option to a string to control the label value.
  1323. *
  1324. * @param string $fieldName Name of a field, like this "Modelname.fieldname"
  1325. * @param array $options Radio button options array.
  1326. * @param array $attributes Array of HTML attributes, and special attributes above.
  1327. * @return string Completed radio widget set.
  1328. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
  1329. */
  1330. public function radio($fieldName, $options = array(), $attributes = array()) {
  1331. $attributes = $this->_initInputField($fieldName, $attributes);
  1332. $showEmpty = $this->_extractOption('empty', $attributes);
  1333. if ($showEmpty) {
  1334. $showEmpty = ($showEmpty === true) ? __d('cake', 'empty') : $showEmpty;
  1335. $options = array('' => $showEmpty) + $options;
  1336. }
  1337. unset($attributes['empty']);
  1338. $legend = false;
  1339. if (isset($attributes['legend'])) {
  1340. $legend = $attributes['legend'];
  1341. unset($attributes['legend']);
  1342. } elseif (count($options) > 1) {
  1343. $legend = __(Inflector::humanize($this->field()));
  1344. }
  1345. $label = true;
  1346. if (isset($attributes['label'])) {
  1347. $label = $attributes['label'];
  1348. unset($attributes['label']);
  1349. }
  1350. $separator = null;
  1351. if (isset($attributes['separator'])) {
  1352. $separator = $attributes['separator'];
  1353. unset($attributes['separator']);
  1354. }
  1355. $between = null;
  1356. if (isset($attributes['between'])) {
  1357. $between = $attributes['between'];
  1358. unset($attributes['between']);
  1359. }
  1360. $value = null;
  1361. if (isset($attributes['value'])) {
  1362. $value = $attributes['value'];
  1363. } else {
  1364. $value = $this->value($fieldName);
  1365. }
  1366. $disabled = array();
  1367. if (isset($attributes['disabled'])) {
  1368. $disabled = $attributes['disabled'];
  1369. }
  1370. $out = array();
  1371. $hiddenField = isset($attributes['hiddenField']) ? $attributes['hiddenField'] : true;
  1372. unset($attributes['hiddenField']);
  1373. if (isset($value) && is_bool($value)) {
  1374. $value = $value ? 1 : 0;
  1375. }
  1376. foreach ($options as $optValue => $optTitle) {
  1377. $optionsHere = array('value' => $optValue);
  1378. if (isset($value) && strval($optValue) === strval($value)) {
  1379. $optionsHere['checked'] = 'checked';
  1380. }
  1381. $isNumeric = is_numeric($optValue);
  1382. if ($disabled && (!is_array($disabled) || in_array((string)$optValue, $disabled, !$isNumeric))) {
  1383. $optionsHere['disabled'] = true;
  1384. }
  1385. $tagName = Inflector::camelize(
  1386. $attributes['id'] . '_' . Inflector::slug($optValue)
  1387. );
  1388. if ($label) {
  1389. $optTitle = $this->Html->useTag('label', $tagName, '', $optTitle);
  1390. }
  1391. if (is_array($between)) {
  1392. $optTitle .= array_shift($between);
  1393. }
  1394. $allOptions = array_merge($attributes, $optionsHere);
  1395. $out[] = $this->Html->useTag('radio', $attributes['name'], $tagName,
  1396. array_diff_key($allOptions, array('name' => null, 'type' => null, 'id' => null)),
  1397. $optTitle
  1398. );
  1399. }
  1400. $hidden = null;
  1401. if ($hiddenField) {
  1402. if (!isset($value) || $value === '') {
  1403. $hidden = $this->hidden($fieldName, array(
  1404. 'id' => $attributes['id'] . '_', 'value' => '', 'name' => $attributes['name']
  1405. ));
  1406. }
  1407. }
  1408. $out = $hidden . implode($separator, $out);
  1409. if (is_array($between)) {
  1410. $between = '';
  1411. }
  1412. if ($legend) {
  1413. $out = $this->Html->useTag('fieldset', '', $this->Html->useTag('legend', $legend) . $between . $out);
  1414. }
  1415. return $out;
  1416. }
  1417. /**
  1418. * Missing method handler - implements various simple input types. Is used to create inputs
  1419. * of various types. e.g. `$this->Form->text();` will create `<input type="text" />` while
  1420. * `$this->Form->range();` will create `<input type="range" />`
  1421. *
  1422. * ### Usage
  1423. *
  1424. * `$this->Form->search('User.query', array('value' => 'test'));`
  1425. *
  1426. * Will make an input like:
  1427. *
  1428. * `<input type="search" id="UserQuery" name="data[User][query]" value="test" />`
  1429. *
  1430. * The first argument to an input type should always be the fieldname, in `Model.field` format.
  1431. * The second argument should always be an array of attributes for the input.
  1432. *
  1433. * @param string $method Method name / input type to make.
  1434. * @param array $params Parameters for the method call
  1435. * @return string Formatted input method.
  1436. * @throws CakeException When there are no params for the method call.
  1437. */
  1438. public function __call($method, $params) {
  1439. $options = array();
  1440. if (empty($params)) {
  1441. throw new CakeException(__d('cake_dev', 'Missing field name for FormHelper::%s', $method));
  1442. }
  1443. if (isset($params[1])) {
  1444. $options = $params[1];
  1445. }
  1446. if (!isset($options['type'])) {
  1447. $options['type'] = $method;
  1448. }
  1449. $options = $this->_initInputField($params[0], $options);
  1450. return $this->Html->useTag('input', $options['name'], array_diff_key($options, array('name' => null)));
  1451. }
  1452. /**
  1453. * Creates a textarea widget.
  1454. *
  1455. * ### Options:
  1456. *
  1457. * - `escape` - Whether or not the contents of the textarea should be escaped. Defaults to true.
  1458. *
  1459. * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
  1460. * @param array $options Array of HTML attributes, and special options above.
  1461. * @return string A generated HTML text input element
  1462. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::textarea
  1463. */
  1464. public function textarea($fieldName, $options = array()) {
  1465. $options = $this->_initInputField($fieldName, $options);
  1466. $value = null;
  1467. if (array_key_exists('value', $options)) {
  1468. $value = $options['value'];
  1469. if (!array_key_exists('escape', $options) || $options['escape'] !== false) {
  1470. $value = h($value);
  1471. }
  1472. unset($options['value']);
  1473. }
  1474. return $this->Html->useTag('textarea', $options['name'], array_diff_key($options, array('type' => null, 'name' => null)), $value);
  1475. }
  1476. /**
  1477. * Creates a hidden input field.
  1478. *
  1479. * @param string $fieldName Name of a field, in the form of "Modelname.fieldname"
  1480. * @param array $options Array of HTML attributes.
  1481. * @return string A generated hidden input
  1482. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hidden
  1483. */
  1484. public function hidden($fieldName, $options = array()) {
  1485. $secure = true;
  1486. if (isset($options['secure'])) {
  1487. $secure = $options['secure'];
  1488. unset($options['secure']);
  1489. }
  1490. $options = $this->_initInputField($fieldName, array_merge(
  1491. $options, array('secure' => self::SECURE_SKIP)
  1492. ));
  1493. if ($secure && $secure !== self::SECURE_SKIP) {
  1494. $this->_secure(true, null, '' . $options['value']);
  1495. }
  1496. return $this->Html->useTag('hidden', $options['name'], array_diff_key($options, array('name' => null)));
  1497. }
  1498. /**
  1499. * Creates file input widget.
  1500. *
  1501. * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
  1502. * @param array $options Array of HTML attributes.
  1503. * @return string A generated file input.
  1504. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::file
  1505. */
  1506. public function file($fieldName, $options = array()) {
  1507. $options += array('secure' => true);
  1508. $secure = $options['secure'];
  1509. $options['secure'] = self::SECURE_SKIP;
  1510. $options = $this->_initInputField($fieldName, $options);
  1511. $field = $this->entity();
  1512. foreach (array('name', 'type', 'tmp_name', 'error', 'size') as $suffix) {
  1513. $this->_secure($secure, array_merge($field, array($suffix)));
  1514. }
  1515. $exclude = array('name' => null, 'value' => null);
  1516. return $this->Html->useTag('file', $options['name'], array_diff_key($options, $exclude));
  1517. }
  1518. /**
  1519. * Creates a `<button>` tag. The type attribute defaults to `type="submit"`
  1520. * You can change it to a different value by using `$options['type']`.
  1521. *
  1522. * ### Options:
  1523. *
  1524. * - `escape` - HTML entity encode the $title of the button. Defaults to false.
  1525. *
  1526. * @param string $title The button's caption. Not automatically HTML encoded
  1527. * @param array $options Array of options and HTML attributes.
  1528. * @return string A HTML button tag.
  1529. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::button
  1530. */
  1531. public function button($title, $options = array()) {
  1532. $options += array('type' => 'submit', 'escape' => false, 'secure' => false);
  1533. if ($options['escape']) {
  1534. $title = h($title);
  1535. }
  1536. if (isset($options['name'])) {
  1537. $name = str_replace(array('[', ']'), array('.', ''), $options['name']);
  1538. $this->_secure($options['secure'], $name);
  1539. }
  1540. return $this->Html->useTag('button', $options, $title);
  1541. }
  1542. /**
  1543. * Create a `<button>` tag with a surrounding `<form>` that submits via POST.
  1544. *
  1545. * This method creates a `<form>` element. So do not use this method in an already opened form.
  1546. * Instead use FormHelper::submit() or FormHelper::button() to create buttons inside opened forms.
  1547. *
  1548. * ### Options:
  1549. *
  1550. * - `data` - Array with key/value to pass in input hidden
  1551. * - Other options is the same of button method.
  1552. *
  1553. * @param string $title The button's caption. Not automatically HTML encoded
  1554. * @param string|array $url URL as string or array
  1555. * @param array $options Array of options and HTML attributes.
  1556. * @return string A HTML button tag.
  1557. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postButton
  1558. */
  1559. public function postButton($title, $url, $options = array()) {
  1560. $out = $this->create(false, array('id' => false, 'url' => $url));
  1561. if (isset($options['data']) && is_array($options['data'])) {
  1562. foreach ($options['data'] as $key => $value) {
  1563. $out .= $this->hidden($key, array('value' => $value, 'id' => false));
  1564. }
  1565. unset($options['data']);
  1566. }
  1567. $out .= $this->button($title, $options);
  1568. $out .= $this->end();
  1569. return $out;
  1570. }
  1571. /**
  1572. * Creates an HTML link, but access the url using the method you specify (defaults to POST).
  1573. * Requires javascript to be enabled in browser.
  1574. *
  1575. * This method creates a `<form>` element. So do not use this method inside an existing form.
  1576. * Instead you should add a submit button using FormHelper::submit()
  1577. *
  1578. * ### Options:
  1579. *
  1580. * - `data` - Array with key/value to pass in input hidden
  1581. * - `confirm` - Can be used instead of $confirmMessage.
  1582. * - Other options is the same of HtmlHelper::link() method.
  1583. * - The option `onclick` will be replaced.
  1584. *
  1585. * @param string $title The content to be wrapped by <a> tags.
  1586. * @param string|array $url Cake-relative URL or array of URL parameters, or external URL (starts with http://)
  1587. * @param array $options Array of HTML attributes.
  1588. * @param string $confirmMessage JavaScript confirmation message.
  1589. * @return string An `<a />` element.
  1590. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postLink
  1591. */
  1592. public function postLink($title, $url = null, $options = array(), $confirmMessage = false) {
  1593. $requestMethod = 'POST';
  1594. if (!empty($options['method'])) {
  1595. $requestMethod = strtoupper($options['method']);
  1596. unset($options['method']);
  1597. }
  1598. if (!empty($options['confirm'])) {
  1599. $confirmMessage = $options['confirm'];
  1600. unset($options['confirm']);
  1601. }
  1602. $formName = uniqid('post_');
  1603. $formUrl = $this->url($url);
  1604. $formOptions = array(
  1605. 'name' => $formName,
  1606. 'id' => $formName,
  1607. 'style' => 'display:none;',
  1608. 'method' => 'post',
  1609. );
  1610. if (isset($options['target'])) {
  1611. $formOptions['target'] = $options['target'];
  1612. unset($options['target']);
  1613. }
  1614. $out = $this->Html->useTag('form', $formUrl, $formOptions);
  1615. $out .= $this->Html->useTag('hidden', '_method', array(
  1616. 'value' => $requestMethod
  1617. ));
  1618. $out .= $this->_csrfField();
  1619. $fields = array();
  1620. if (isset($options['data']) && is_array($options['data'])) {
  1621. foreach ($options['data'] as $key => $value) {
  1622. $fields[$key] = $value;
  1623. $out .= $this->hidden($key, array('value' => $value, 'id' => false));
  1624. }
  1625. unset($options['data']);
  1626. }
  1627. $out .= $this->secure($fields);
  1628. $out .= $this->Html->useTag('formend');
  1629. $url = '#';
  1630. $onClick = 'document.' . $formName . '.submit();';
  1631. if ($confirmMessage) {
  1632. $confirmMessage = str_replace(array("'", '"'), array("\'", '\"'), $confirmMessage);
  1633. $options['onclick'] = "if (confirm('{$confirmMessage}')) { {$onClick} }";
  1634. } else {
  1635. $options['onclick'] = $onClick;
  1636. }
  1637. $options['onclick'] .= ' event.returnValue = false; return false;';
  1638. $out .= $this->Html->link($title, $url, $options);
  1639. return $out;
  1640. }
  1641. /**
  1642. * Creates a submit button element. This method will generate `<input />` elements that
  1643. * can be used to submit, and reset forms by using $options. image submits can be created by supplying an
  1644. * image path for $caption.
  1645. *
  1646. * ### Options
  1647. *
  1648. * - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to
  1649. * FormHelper::input().
  1650. * - `before` - Content to include before the input.
  1651. * - `after` - Content to include after the input.
  1652. * - `type` - Set to 'reset' for reset inputs. Defaults to 'submit'
  1653. * - Other attributes will be assigned to the input element.
  1654. *
  1655. * ### Options
  1656. *
  1657. * - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to
  1658. * FormHelper::input().
  1659. * - Other attributes will be assigned to the input element.
  1660. *
  1661. * @param string $caption The label appearing on the button OR if string contains :// or the
  1662. * extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension
  1663. * exists, AND the first character is /, image is relative to webroot,
  1664. * OR if the first character is not /, image is relative to webroot/img.
  1665. * @param array $options Array of options. See above.
  1666. * @return string A HTML submit button
  1667. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::submit
  1668. */
  1669. public function submit($caption = null, $options = array()) {
  1670. if (!is_string($caption) && empty($caption)) {
  1671. $caption = __d('cake', 'Submit');
  1672. }
  1673. $out = null;
  1674. $div = true;
  1675. if (isset($options['div'])) {
  1676. $div = $options['div'];
  1677. unset($options['div']);
  1678. }
  1679. $options += array('type' => 'submit', 'before' => null, 'after' => null, 'secure' => false);
  1680. $divOptions = array('tag' => 'div');
  1681. if ($div === true) {
  1682. $divOptions['class'] = 'submit';
  1683. } elseif ($div === false) {
  1684. unset($divOptions);
  1685. } elseif (is_string($div)) {
  1686. $divOptions['class'] = $div;
  1687. } elseif (is_array($div)) {
  1688. $divOptions = array_merge(array('class' => 'submit', 'tag' => 'div'), $div);
  1689. }
  1690. if (isset($options['name'])) {
  1691. $name = str_replace(array('[', ']'), array('.', ''), $options['name']);
  1692. $this->_secure($options['secure'], $name);
  1693. }
  1694. unset($options['secure']);
  1695. $before = $options['before'];
  1696. $after = $options['after'];
  1697. unset($options['before'], $options['after']);
  1698. $isUrl = strpos($caption, '://') !== false;
  1699. $isImage = preg_match('/\.(jpg|jpe|jpeg|gif|png|ico)$/', $caption);
  1700. if ($isUrl || $isImage) {
  1701. $unlockFields = array('x', 'y');
  1702. if (isset($options['name'])) {
  1703. $unlockFields = array(
  1704. $options['name'] . '_x', $options['name'] . '_y'
  1705. );
  1706. }
  1707. foreach ($unlockFields as $ignore) {
  1708. $this->unlockField($ignore);
  1709. }
  1710. }
  1711. if ($isUrl) {
  1712. unset($options['type']);
  1713. $tag = $this->Html->useTag('submitimage', $caption, $options);
  1714. } elseif ($isImage) {
  1715. unset($options['type']);
  1716. if ($caption{0} !== '/') {
  1717. $url = $this->webroot(IMAGES_URL . $caption);
  1718. } else {
  1719. $url = $this->webroot(trim($caption, '/'));
  1720. }
  1721. $url = $this->assetTimestamp($url);
  1722. $tag = $this->Html->useTag('submitimage', $url, $options);
  1723. } else {
  1724. $options['value'] = $caption;
  1725. $tag = $this->Html->useTag('submit', $options);
  1726. }
  1727. $out = $before . $tag . $after;
  1728. if (isset($divOptions)) {
  1729. $tag = $divOptions['tag'];
  1730. unset($divOptions['tag']);
  1731. $out = $this->Html->tag($tag, $out, $divOptions);
  1732. }
  1733. return $out;
  1734. }
  1735. /**
  1736. * Returns a formatted SELECT element.
  1737. *
  1738. * ### Attributes:
  1739. *
  1740. * - `showParents` - If included in the array and set to true, an additional option element
  1741. * will be added for the parent of each option group. You can set an option with the same name
  1742. * and it's key will be used for the value of the option.
  1743. * - `multiple` - show a multiple select box. If set to 'checkbox' multiple checkboxes will be
  1744. * created instead.
  1745. * - `empty` - If true, the empty select option is shown. If a string,
  1746. * that string is displayed as the empty element.
  1747. * - `escape` - If true contents of options will be HTML entity encoded. Defaults to true.
  1748. * - `value` The selected value of the input.
  1749. * - `class` - When using multiple = checkbox the classname to apply to the divs. Defaults to 'checkbox'.
  1750. * - `disabled` - Control the disabled attribute. When creating a select box, set to true to disable the
  1751. * select box. When creating checkboxes, `true` will disable all checkboxes. You can also set disabled
  1752. * to a list of values you want to disable when creating checkboxes.
  1753. *
  1754. * ### Using options
  1755. *
  1756. * A simple array will create normal options:
  1757. *
  1758. * {{{
  1759. * $options = array(1 => 'one', 2 => 'two);
  1760. * $this->Form->select('Model.field', $options));
  1761. * }}}
  1762. *
  1763. * While a nested options array will create optgroups with options inside them.
  1764. * {{{
  1765. * $options = array(
  1766. * 1 => 'bill',
  1767. * 'fred' => array(
  1768. * 2 => 'fred',
  1769. * 3 => 'fred jr.'
  1770. * )
  1771. * );
  1772. * $this->Form->select('Model.field', $options);
  1773. * }}}
  1774. *
  1775. * In the above `2 => 'fred'` will not generate an option element. You should enable the `showParents`
  1776. * attribute to show the fred option.
  1777. *
  1778. * If you have multiple options that need to have the same value attribute, you can
  1779. * use an array of arrays to express this:
  1780. *
  1781. * {{{
  1782. * $options = array(
  1783. * array('name' => 'United states', 'value' => 'USA'),
  1784. * array('name' => 'USA', 'value' => 'USA'),
  1785. * );
  1786. * }}}
  1787. *
  1788. * @param string $fieldName Name attribute of the SELECT
  1789. * @param array $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the
  1790. * SELECT element
  1791. * @param array $attributes The HTML attributes of the select element.
  1792. * @return string Formatted SELECT element
  1793. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
  1794. */
  1795. public function select($fieldName, $options = array(), $attributes = array()) {
  1796. $select = array();
  1797. $style = null;
  1798. $tag = null;
  1799. $attributes += array(
  1800. 'class' => null,
  1801. 'escape' => true,
  1802. 'secure' => true,
  1803. 'empty' => '',
  1804. 'showParents' => false,
  1805. 'hiddenField' => true,
  1806. 'disabled' => false
  1807. );
  1808. $escapeOptions = $this->_extractOption('escape', $attributes);
  1809. $secure = $this->_extractOption('secure', $attributes);
  1810. $showEmpty = $this->_extractOption('empty', $attributes);
  1811. $showParents = $this->_extractOption('showParents', $attributes);
  1812. $hiddenField = $this->_extractOption('hiddenField', $attributes);
  1813. unset($attributes['escape'], $attributes['secure'], $attributes['empty'], $attributes['showParents'], $attributes['hiddenField']);
  1814. $id = $this->_extractOption('id', $attributes);
  1815. $attributes = $this->_initInputField($fieldName, array_merge(
  1816. (array)$attributes, array('secure' => self::SECURE_SKIP)
  1817. ));
  1818. if (is_string($options) && isset($this->_options[$options])) {
  1819. $options = $this->_generateOptions($options);
  1820. } elseif (!is_array($options)) {
  1821. $options = array();
  1822. }
  1823. if (isset($attributes['type'])) {
  1824. unset($attributes['type']);
  1825. }
  1826. if (!empty($attributes['multiple'])) {
  1827. $style = ($attributes['multiple'] === 'checkbox') ? 'checkbox' : null;
  1828. $template = ($style) ? 'checkboxmultiplestart' : 'selectmultiplestart';
  1829. $tag = $template;
  1830. if ($hiddenField) {
  1831. $hiddenAttributes = array(
  1832. 'value' => '',
  1833. 'id' => $attributes['id'] . ($style ? '' : '_'),
  1834. 'secure' => false,
  1835. 'name' => $attributes['name']
  1836. );
  1837. $select[] = $this->hidden(null, $hiddenAttributes);
  1838. }
  1839. } else {
  1840. $tag = 'selectstart';
  1841. }
  1842. if (!empty($tag) || isset($template)) {
  1843. $hasOptions = (count($options) > 0 || $showEmpty);
  1844. // Secure the field if there are options, or its a multi select.
  1845. // Single selects with no options don't submit, but multiselects do.
  1846. if (
  1847. (!isset($secure) || $secure) &&
  1848. empty($attributes['disabled']) &&
  1849. (!empty($attributes['multiple']) || $hasOptions)
  1850. ) {
  1851. $this->_secure(true);
  1852. }
  1853. $select[] = $this->Html->useTag($tag, $attributes['name'], array_diff_key($attributes, array('name' => null, 'value' => null)));
  1854. }
  1855. $emptyMulti = (
  1856. $showEmpty !== null && $showEmpty !== false && !(
  1857. empty($showEmpty) && (isset($attributes) &&
  1858. array_key_exists('multiple', $attributes))
  1859. )
  1860. );
  1861. if ($emptyMulti) {
  1862. $showEmpty = ($showEmpty === true) ? '' : $showEmpty;
  1863. $options = array('' => $showEmpty) + $options;
  1864. }
  1865. if (!$id) {
  1866. $attributes['id'] = Inflector::camelize($attributes['id']);
  1867. }
  1868. $select = array_merge($select, $this->_selectOptions(
  1869. array_reverse($options, true),
  1870. array(),
  1871. $showParents,
  1872. array(
  1873. 'escape' => $escapeOptions,
  1874. 'style' => $style,
  1875. 'name' => $attributes['name'],
  1876. 'value' => $attributes['value'],
  1877. 'class' => $attributes['class'],
  1878. 'id' => $attributes['id'],
  1879. 'disabled' => $attributes['disabled'],
  1880. )
  1881. ));
  1882. $template = ($style === 'checkbox') ? 'checkboxmultipleend' : 'selectend';
  1883. $select[] = $this->Html->useTag($template);
  1884. return implode("\n", $select);
  1885. }
  1886. /**
  1887. * Returns a SELECT element for days.
  1888. *
  1889. * ### Attributes:
  1890. *
  1891. * - `empty` - If true, the empty select option is shown. If a string,
  1892. * that string is displayed as the empty element.
  1893. * - `value` The selected value of the input.
  1894. *
  1895. * @param string $fieldName Prefix name for the SELECT element
  1896. * @param array $attributes HTML attributes for the select element
  1897. * @return string A generated day select box.
  1898. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::day
  1899. */
  1900. public function day($fieldName = null, $attributes = array()) {
  1901. $attributes += array('empty' => true, 'value' => null);
  1902. $attributes = $this->_dateTimeSelected('day', $fieldName, $attributes);
  1903. if (strlen($attributes['value']) > 2) {
  1904. $attributes['value'] = date_create($attributes['value'])->format('d');
  1905. } elseif ($attributes['value'] === false) {
  1906. $attributes['value'] = null;
  1907. }
  1908. return $this->select($fieldName . ".day", $this->_generateOptions('day'), $attributes);
  1909. }
  1910. /**
  1911. * Returns a SELECT element for years
  1912. *
  1913. * ### Attributes:
  1914. *
  1915. * - `empty` - If true, the empty select option is shown. If a string,
  1916. * that string is displayed as the empty element.
  1917. * - `orderYear` - Ordering of year values in select options.
  1918. * Possible values 'asc', 'desc'. Default 'desc'
  1919. * - `value` The selected value of the input.
  1920. *
  1921. * @param string $fieldName Prefix name for the SELECT element
  1922. * @param integer $minYear First year in sequence
  1923. * @param integer $maxYear Last year in sequence
  1924. * @param array $attributes Attribute array for the select elements.
  1925. * @return string Completed year select input
  1926. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::year
  1927. */
  1928. public function year($fieldName, $minYear = null, $maxYear = null, $attributes = array()) {
  1929. $attributes += array('empty' => true, 'value' => null);
  1930. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  1931. if (is_array($value)) {
  1932. extract($value);
  1933. $attributes['value'] = $year;
  1934. } else {
  1935. if (empty($value)) {
  1936. if (!$attributes['empty'] && !$maxYear) {
  1937. $attributes['value'] = 'now';
  1938. } elseif (!$attributes['empty'] && $maxYear && !$attributes['value']) {
  1939. $attributes['value'] = $maxYear;
  1940. }
  1941. } else {
  1942. $attributes['value'] = $value;
  1943. }
  1944. }
  1945. }
  1946. if (strlen($attributes['value']) > 4 || $attributes['value'] === 'now') {
  1947. $attributes['value'] = date_create($attributes['value'])->format('Y');
  1948. } elseif ($attributes['value'] === false) {
  1949. $attributes['value'] = null;
  1950. }
  1951. $yearOptions = array('value' => $attributes['value'], 'min' => $minYear, 'max' => $maxYear, 'order' => 'desc');
  1952. if (isset($attributes['orderYear'])) {
  1953. $yearOptions['order'] = $attributes['orderYear'];
  1954. unset($attributes['orderYear']);
  1955. }
  1956. return $this->select(
  1957. $fieldName . '.year', $this->_generateOptions('year', $yearOptions),
  1958. $attributes
  1959. );
  1960. }
  1961. /**
  1962. * Returns a SELECT element for months.
  1963. *
  1964. * ### Attributes:
  1965. *
  1966. * - `monthNames` - If false, 2 digit numbers will be used instead of text.
  1967. * If a array, the given array will be used.
  1968. * - `empty` - If true, the empty select option is shown. If a string,
  1969. * that string is displayed as the empty element.
  1970. * - `value` The selected value of the input.
  1971. *
  1972. * @param string $fieldName Prefix name for the SELECT element
  1973. * @param array $attributes Attributes for the select element
  1974. * @return string A generated month select dropdown.
  1975. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::month
  1976. */
  1977. public function month($fieldName, $attributes = array()) {
  1978. $attributes += array('empty' => true, 'value' => null);
  1979. $attributes = $this->_dateTimeSelected('month', $fieldName, $attributes);
  1980. if (strlen($attributes['value']) > 2) {
  1981. $attributes['value'] = date_create($attributes['value'])->format('m');
  1982. } elseif ($attributes['value'] === false) {
  1983. $attributes['value'] = null;
  1984. }
  1985. $defaults = array('monthNames' => true);
  1986. $attributes = array_merge($defaults, (array)$attributes);
  1987. $monthNames = $attributes['monthNames'];
  1988. unset($attributes['monthNames']);
  1989. return $this->select(
  1990. $fieldName . ".month",
  1991. $this->_generateOptions('month', array('monthNames' => $monthNames)),
  1992. $attributes
  1993. );
  1994. }
  1995. /**
  1996. * Returns a SELECT element for hours.
  1997. *
  1998. * ### Attributes:
  1999. *
  2000. * - `empty` - If true, the empty select option is shown. If a string,
  2001. * that string is displayed as the empty element.
  2002. * - `value` The selected value of the input.
  2003. *
  2004. * @param string $fieldName Prefix name for the SELECT element
  2005. * @param boolean $format24Hours True for 24 hours format
  2006. * @param array $attributes List of HTML attributes
  2007. * @return string Completed hour select input
  2008. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hour
  2009. */
  2010. public function hour($fieldName, $format24Hours = false, $attributes = array()) {
  2011. $attributes += array('empty' => true, 'value' => null);
  2012. $attributes = $this->_dateTimeSelected('hour', $fieldName, $attributes);
  2013. if (strlen($attributes['value']) > 2) {
  2014. $Date = new DateTime($attributes['value']);
  2015. if ($format24Hours) {
  2016. $attributes['value'] = $Date->format('H');
  2017. } else {
  2018. $attributes['value'] = $Date->format('g');
  2019. }
  2020. } elseif ($attributes['value'] === false) {
  2021. $attributes['value'] = null;
  2022. }
  2023. if ($attributes['value'] > 12 && !$format24Hours) {
  2024. $attributes['value'] -= 12;
  2025. }
  2026. if ($attributes['value'] === '00' && !$format24Hours) {
  2027. $attributes['value'] = 12;
  2028. }
  2029. return $this->select(
  2030. $fieldName . ".hour",
  2031. $this->_generateOptions($format24Hours ? 'hour24' : 'hour'),
  2032. $attributes
  2033. );
  2034. }
  2035. /**
  2036. * Returns a SELECT element for minutes.
  2037. *
  2038. * ### Attributes:
  2039. *
  2040. * - `empty` - If true, the empty select option is shown. If a string,
  2041. * that string is displayed as the empty element.
  2042. * - `value` The selected value of the input.
  2043. *
  2044. * @param string $fieldName Prefix name for the SELECT element
  2045. * @param string $attributes Array of Attributes
  2046. * @return string Completed minute select input.
  2047. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::minute
  2048. */
  2049. public function minute($fieldName, $attributes = array()) {
  2050. $attributes += array('empty' => true, 'value' => null);
  2051. $attributes = $this->_dateTimeSelected('min', $fieldName, $attributes);
  2052. if (strlen($attributes['value']) > 2) {
  2053. $attributes['value'] = date_create($attributes['value'])->format('i');
  2054. } elseif ($attributes['value'] === false) {
  2055. $attributes['value'] = null;
  2056. }
  2057. $minuteOptions = array();
  2058. if (isset($attributes['interval'])) {
  2059. $minuteOptions['interval'] = $attributes['interval'];
  2060. unset($attributes['interval']);
  2061. }
  2062. return $this->select(
  2063. $fieldName . ".min", $this->_generateOptions('minute', $minuteOptions),
  2064. $attributes
  2065. );
  2066. }
  2067. /**
  2068. * Selects values for dateTime selects.
  2069. *
  2070. * @param string $select Name of element field. ex. 'day'
  2071. * @param string $fieldName Name of fieldName being generated ex. Model.created
  2072. * @param array $attributes Array of attributes, must contain 'empty' key.
  2073. * @return array Attributes array with currently selected value.
  2074. */
  2075. protected function _dateTimeSelected($select, $fieldName, $attributes) {
  2076. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  2077. if (is_array($value) && isset($value[$select])) {
  2078. $attributes['value'] = $value[$select];
  2079. } else {
  2080. if (empty($value)) {
  2081. if (!$attributes['empty']) {
  2082. $attributes['value'] = 'now';
  2083. }
  2084. } else {
  2085. $attributes['value'] = $value;
  2086. }
  2087. }
  2088. }
  2089. return $attributes;
  2090. }
  2091. /**
  2092. * Returns a SELECT element for AM or PM.
  2093. *
  2094. * ### Attributes:
  2095. *
  2096. * - `empty` - If true, the empty select option is shown. If a string,
  2097. * that string is displayed as the empty element.
  2098. * - `value` The selected value of the input.
  2099. *
  2100. * @param string $fieldName Prefix name for the SELECT element
  2101. * @param string $attributes Array of Attributes
  2102. * @return string Completed meridian select input
  2103. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::meridian
  2104. */
  2105. public function meridian($fieldName, $attributes = array()) {
  2106. $attributes += array('empty' => true, 'value' => null);
  2107. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  2108. if (is_array($value)) {
  2109. extract($value);
  2110. $attributes['value'] = $meridian;
  2111. } else {
  2112. if (empty($value)) {
  2113. if (!$attributes['empty']) {
  2114. $attributes['value'] = date('a');
  2115. }
  2116. } else {
  2117. $attributes['value'] = date_create($attributes['value'])->format('a');
  2118. }
  2119. }
  2120. }
  2121. if ($attributes['value'] === false) {
  2122. $attributes['value'] = null;
  2123. }
  2124. return $this->select(
  2125. $fieldName . ".meridian", $this->_generateOptions('meridian'),
  2126. $attributes
  2127. );
  2128. }
  2129. /**
  2130. * Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
  2131. *
  2132. * ### Attributes:
  2133. *
  2134. * - `monthNames` If false, 2 digit numbers will be used instead of text.
  2135. * If a array, the given array will be used.
  2136. * - `minYear` The lowest year to use in the year select
  2137. * - `maxYear` The maximum year to use in the year select
  2138. * - `interval` The interval for the minutes select. Defaults to 1
  2139. * - `separator` The contents of the string between select elements. Defaults to '-'
  2140. * - `empty` - If true, the empty select option is shown. If a string,
  2141. * that string is displayed as the empty element.
  2142. * - `value` | `default` The default value to be used by the input. A value in `$this->data`
  2143. * matching the field name will override this value. If no default is provided `time()` will be used.
  2144. *
  2145. * @param string $fieldName Prefix name for the SELECT element
  2146. * @param string $dateFormat DMY, MDY, YMD, or null to not generate date inputs.
  2147. * @param string $timeFormat 12, 24, or null to not generate time inputs.
  2148. * @param string $attributes array of Attributes
  2149. * @return string Generated set of select boxes for the date and time formats chosen.
  2150. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::dateTime
  2151. */
  2152. public function dateTime($fieldName, $dateFormat = 'DMY', $timeFormat = '12', $attributes = array()) {
  2153. $attributes += array('empty' => true, 'value' => null);
  2154. $year = $month = $day = $hour = $min = $meridian = null;
  2155. if (empty($attributes['value'])) {
  2156. $attributes = $this->value($attributes, $fieldName);
  2157. }
  2158. if ($attributes['value'] === null && $attributes['empty'] != true) {
  2159. $attributes['value'] = time();
  2160. }
  2161. if (!empty($attributes['value'])) {
  2162. list($year, $month, $day, $hour, $min, $meridian) = $this->_getDateTimeValue(
  2163. $attributes['value'],
  2164. $timeFormat
  2165. );
  2166. }
  2167. $defaults = array(
  2168. 'minYear' => null, 'maxYear' => null, 'separator' => '-',
  2169. 'interval' => 1, 'monthNames' => true
  2170. );
  2171. $attributes = array_merge($defaults, (array)$attributes);
  2172. if (isset($attributes['minuteInterval'])) {
  2173. $attributes['interval'] = $attributes['minuteInterval'];
  2174. unset($attributes['minuteInterval']);
  2175. }
  2176. $minYear = $attributes['minYear'];
  2177. $maxYear = $attributes['maxYear'];
  2178. $separator = $attributes['separator'];
  2179. $interval = $attributes['interval'];
  2180. $monthNames = $attributes['monthNames'];
  2181. $attributes = array_diff_key($attributes, $defaults);
  2182. if (!empty($interval) && $interval > 1 && !empty($min)) {
  2183. $current = new DateTime();
  2184. if ($year !== null) {
  2185. $current->setDate($year, $month, $day);
  2186. }
  2187. if ($hour !== null) {
  2188. $current->setTime($hour, $min);
  2189. }
  2190. $change = (round($min * (1 / $interval)) * $interval) - $min;
  2191. $current->modify($change > 0 ? "+$change minutes" : "$change minutes");
  2192. $format = ($timeFormat === '12') ? 'Y m d h i a' : 'Y m d H i a';
  2193. $newTime = explode(' ', $current->format($format));
  2194. list($year, $month, $day, $hour, $min, $meridian) = $newTime;
  2195. }
  2196. $keys = array('Day', 'Month', 'Year', 'Hour', 'Minute', 'Meridian');
  2197. $attrs = array_fill_keys($keys, $attributes);
  2198. $hasId = isset($attributes['id']);
  2199. if ($hasId && is_array($attributes['id'])) {
  2200. // check for missing ones and build selectAttr for each element
  2201. $attributes['id'] += array(
  2202. 'month' => '',
  2203. 'year' => '',
  2204. 'day' => '',
  2205. 'hour' => '',
  2206. 'minute' => '',
  2207. 'meridian' => ''
  2208. );
  2209. foreach ($keys as $key) {
  2210. $attrs[$key]['id'] = $attributes['id'][strtolower($key)];
  2211. }
  2212. }
  2213. if ($hasId && is_string($attributes['id'])) {
  2214. // build out an array version
  2215. foreach ($keys as $key) {
  2216. $attrs[$key]['id'] = $attributes['id'] . $key;
  2217. }
  2218. }
  2219. if (is_array($attributes['empty'])) {
  2220. $attributes['empty'] += array(
  2221. 'month' => true,
  2222. 'year' => true,
  2223. 'day' => true,
  2224. 'hour' => true,
  2225. 'minute' => true,
  2226. 'meridian' => true
  2227. );
  2228. foreach ($keys as $key) {
  2229. $attrs[$key]['empty'] = $attributes['empty'][strtolower($key)];
  2230. }
  2231. }
  2232. $selects = array();
  2233. foreach (preg_split('//', $dateFormat, -1, PREG_SPLIT_NO_EMPTY) as $char) {
  2234. switch ($char) {
  2235. case 'Y':
  2236. $attrs['Year']['value'] = $year;
  2237. $selects[] = $this->year(
  2238. $fieldName, $minYear, $maxYear, $attrs['Year']
  2239. );
  2240. break;
  2241. case 'M':
  2242. $attrs['Month']['value'] = $month;
  2243. $attrs['Month']['monthNames'] = $monthNames;
  2244. $selects[] = $this->month($fieldName, $attrs['Month']);
  2245. break;
  2246. case 'D':
  2247. $attrs['Day']['value'] = $day;
  2248. $selects[] = $this->day($fieldName, $attrs['Day']);
  2249. break;
  2250. }
  2251. }
  2252. $opt = implode($separator, $selects);
  2253. $attrs['Minute']['interval'] = $interval;
  2254. switch ($timeFormat) {
  2255. case '24':
  2256. $attrs['Hour']['value'] = $hour;
  2257. $attrs['Minute']['value'] = $min;
  2258. $opt .= $this->hour($fieldName, true, $attrs['Hour']) . ':' .
  2259. $this->minute($fieldName, $attrs['Minute']);
  2260. break;
  2261. case '12':
  2262. $attrs['Hour']['value'] = $hour;
  2263. $attrs['Minute']['value'] = $min;
  2264. $attrs['Meridian']['value'] = $meridian;
  2265. $opt .= $this->hour($fieldName, false, $attrs['Hour']) . ':' .
  2266. $this->minute($fieldName, $attrs['Minute']) . ' ' .
  2267. $this->meridian($fieldName, $attrs['Meridian']);
  2268. break;
  2269. }
  2270. return $opt;
  2271. }
  2272. /**
  2273. * Parse the value for a datetime selected value
  2274. *
  2275. * @param string|array $value The selected value.
  2276. * @param integer $timeFormat The time format
  2277. * @return array Array of selected value.
  2278. */
  2279. protected function _getDateTimeValue($value, $timeFormat) {
  2280. $year = $month = $day = $hour = $min = $meridian = null;
  2281. if (is_array($value)) {
  2282. extract($value);
  2283. if ($meridian === 'pm') {
  2284. $hour += 12;
  2285. }
  2286. return array($year, $month, $day, $hour, $min, $meridian);
  2287. }
  2288. if (is_numeric($value)) {
  2289. $value = strftime('%Y-%m-%d %H:%M:%S', $value);
  2290. }
  2291. $meridian = 'am';
  2292. $pos = strpos($value, '-');
  2293. if ($pos !== false) {
  2294. $date = explode('-', $value);
  2295. $days = explode(' ', $date[2]);
  2296. $day = $days[0];
  2297. $month = $date[1];
  2298. $year = $date[0];
  2299. } else {
  2300. $days[1] = $value;
  2301. }
  2302. if (!empty($timeFormat)) {
  2303. $time = explode(':', $days[1]);
  2304. if ($time[0] >= 12 && $timeFormat == 12) {
  2305. $meridian = 'pm';
  2306. } elseif ($time[0] === '00' && $timeFormat == 12) {
  2307. $time[0] = 12;
  2308. } elseif ($time[0] >= 12) {
  2309. $meridian = 'pm';
  2310. }
  2311. if ($time[0] == 0 && $timeFormat == 12) {
  2312. $time[0] = 12;
  2313. }
  2314. $hour = $min = null;
  2315. if (isset($time[1])) {
  2316. $hour = $time[0];
  2317. $min = $time[1];
  2318. }
  2319. }
  2320. return array($year, $month, $day, $hour, $min, $meridian);
  2321. }
  2322. /**
  2323. * Gets the input field name for the current tag
  2324. *
  2325. * @param array $options
  2326. * @param string $field
  2327. * @param string $key
  2328. * @return array
  2329. */
  2330. protected function _name($options = array(), $field = null, $key = 'name') {
  2331. if ($this->requestType === 'get') {
  2332. if ($options === null) {
  2333. $options = array();
  2334. } elseif (is_string($options)) {
  2335. $field = $options;
  2336. $options = 0;
  2337. }
  2338. if (!empty($field)) {
  2339. $this->setEntity($field);
  2340. }
  2341. if (is_array($options) && isset($options[$key])) {
  2342. return $options;
  2343. }
  2344. $entity = $this->entity();
  2345. $model = $this->model();
  2346. $name = $model === $entity[0] && isset($entity[1]) ? $entity[1] : $entity[0];
  2347. $last = $entity[count($entity) - 1];
  2348. if (in_array($last, $this->_fieldSuffixes)) {
  2349. $name .= '[' . $last . ']';
  2350. }
  2351. if (is_array($options)) {
  2352. $options[$key] = $name;
  2353. return $options;
  2354. } else {
  2355. return $name;
  2356. }
  2357. }
  2358. return parent::_name($options, $field, $key);
  2359. }
  2360. /**
  2361. * Returns an array of formatted OPTION/OPTGROUP elements
  2362. *
  2363. * @param array $elements
  2364. * @param array $parents
  2365. * @param boolean $showParents
  2366. * @param array $attributes
  2367. * @return array
  2368. */
  2369. protected function _selectOptions($elements = array(), $parents = array(), $showParents = null, $attributes = array()) {
  2370. $select = array();
  2371. $attributes = array_merge(
  2372. array('escape' => true, 'style' => null, 'value' => null, 'class' => null),
  2373. $attributes
  2374. );
  2375. $selectedIsEmpty = ($attributes['value'] === '' || $attributes['value'] === null);
  2376. $selectedIsArray = is_array($attributes['value']);
  2377. foreach ($elements as $name => $title) {
  2378. $htmlOptions = array();
  2379. if (is_array($title) && (!isset($title['name']) || !isset($title['value']))) {
  2380. if (!empty($name)) {
  2381. if ($attributes['style'] === 'checkbox') {
  2382. $select[] = $this->Html->useTag('fieldsetend');
  2383. } else {
  2384. $select[] = $this->Html->useTag('optiongroupend');
  2385. }
  2386. $parents[] = $name;
  2387. }
  2388. $select = array_merge($select, $this->_selectOptions(
  2389. $title, $parents, $showParents, $attributes
  2390. ));
  2391. if (!empty($name)) {
  2392. $name = $attributes['escape'] ? h($name) : $name;
  2393. if ($attributes['style'] === 'checkbox') {
  2394. $select[] = $this->Html->useTag('fieldsetstart', $name);
  2395. } else {
  2396. $select[] = $this->Html->useTag('optiongroup', $name, '');
  2397. }
  2398. }
  2399. $name = null;
  2400. } elseif (is_array($title)) {
  2401. $htmlOptions = $title;
  2402. $name = $title['value'];
  2403. $title = $title['name'];
  2404. unset($htmlOptions['name'], $htmlOptions['value']);
  2405. }
  2406. if ($name !== null) {
  2407. $isNumeric = is_numeric($name);
  2408. if (
  2409. (!$selectedIsArray && !$selectedIsEmpty && (string)$attributes['value'] == (string)$name) ||
  2410. ($selectedIsArray && in_array((string)$name, $attributes['value'], !$isNumeric))
  2411. ) {
  2412. if ($attributes['style'] === 'checkbox') {
  2413. $htmlOptions['checked'] = true;
  2414. } else {
  2415. $htmlOptions['selected'] = 'selected';
  2416. }
  2417. }
  2418. if ($showParents || (!in_array($title, $parents))) {
  2419. $title = ($attributes['escape']) ? h($title) : $title;
  2420. $hasDisabled = !empty($attributes['disabled']);
  2421. if ($hasDisabled) {
  2422. $disabledIsArray = is_array($attributes['disabled']);
  2423. if ($disabledIsArray) {
  2424. $disabledIsNumeric = is_numeric($name);
  2425. }
  2426. }
  2427. if (
  2428. $hasDisabled &&
  2429. $disabledIsArray &&
  2430. in_array((string)$name, $attributes['disabled'], !$disabledIsNumeric)
  2431. ) {
  2432. $htmlOptions['disabled'] = 'disabled';
  2433. }
  2434. if ($hasDisabled && !$disabledIsArray) {
  2435. $htmlOptions['disabled'] = $attributes['disabled'] === true ? 'disabled' : $attributes['disabled'];
  2436. }
  2437. if ($attributes['style'] === 'checkbox') {
  2438. $htmlOptions['value'] = $name;
  2439. $tagName = $attributes['id'] . Inflector::camelize(Inflector::slug($name));
  2440. $htmlOptions['id'] = $tagName;
  2441. $label = array('for' => $tagName);
  2442. if (isset($htmlOptions['checked']) && $htmlOptions['checked'] === true) {
  2443. $label['class'] = 'selected';
  2444. }
  2445. $name = $attributes['name'];
  2446. if (empty($attributes['class'])) {
  2447. $attributes['class'] = 'checkbox';
  2448. } elseif ($attributes['class'] === 'form-error') {
  2449. $attributes['class'] = 'checkbox ' . $attributes['class'];
  2450. }
  2451. $label = $this->label(null, $title, $label);
  2452. $item = $this->Html->useTag('checkboxmultiple', $name, $htmlOptions);
  2453. $select[] = $this->Html->div($attributes['class'], $item . $label);
  2454. } else {
  2455. $select[] = $this->Html->useTag('selectoption', $name, $htmlOptions, $title);
  2456. }
  2457. }
  2458. }
  2459. }
  2460. return array_reverse($select, true);
  2461. }
  2462. /**
  2463. * Generates option lists for common <select /> menus
  2464. *
  2465. * @param string $name
  2466. * @param array $options
  2467. * @return array
  2468. */
  2469. protected function _generateOptions($name, $options = array()) {
  2470. if (!empty($this->options[$name])) {
  2471. return $this->options[$name];
  2472. }
  2473. $data = array();
  2474. switch ($name) {
  2475. case 'minute':
  2476. if (isset($options['interval'])) {
  2477. $interval = $options['interval'];
  2478. } else {
  2479. $interval = 1;
  2480. }
  2481. $i = 0;
  2482. while ($i < 60) {
  2483. $data[sprintf('%02d', $i)] = sprintf('%02d', $i);
  2484. $i += $interval;
  2485. }
  2486. break;
  2487. case 'hour':
  2488. for ($i = 1; $i <= 12; $i++) {
  2489. $data[sprintf('%02d', $i)] = $i;
  2490. }
  2491. break;
  2492. case 'hour24':
  2493. for ($i = 0; $i <= 23; $i++) {
  2494. $data[sprintf('%02d', $i)] = $i;
  2495. }
  2496. break;
  2497. case 'meridian':
  2498. $data = array('am' => 'am', 'pm' => 'pm');
  2499. break;
  2500. case 'day':
  2501. $min = 1;
  2502. $max = 31;
  2503. if (isset($options['min'])) {
  2504. $min = $options['min'];
  2505. }
  2506. if (isset($options['max'])) {
  2507. $max = $options['max'];
  2508. }
  2509. for ($i = $min; $i <= $max; $i++) {
  2510. $data[sprintf('%02d', $i)] = $i;
  2511. }
  2512. break;
  2513. case 'month':
  2514. if ($options['monthNames'] === true) {
  2515. $data['01'] = __d('cake', 'January');
  2516. $data['02'] = __d('cake', 'February');
  2517. $data['03'] = __d('cake', 'March');
  2518. $data['04'] = __d('cake', 'April');
  2519. $data['05'] = __d('cake', 'May');
  2520. $data['06'] = __d('cake', 'June');
  2521. $data['07'] = __d('cake', 'July');
  2522. $data['08'] = __d('cake', 'August');
  2523. $data['09'] = __d('cake', 'September');
  2524. $data['10'] = __d('cake', 'October');
  2525. $data['11'] = __d('cake', 'November');
  2526. $data['12'] = __d('cake', 'December');
  2527. } elseif (is_array($options['monthNames'])) {
  2528. $data = $options['monthNames'];
  2529. } else {
  2530. for ($m = 1; $m <= 12; $m++) {
  2531. $data[sprintf("%02s", $m)] = strftime("%m", mktime(1, 1, 1, $m, 1, 1999));
  2532. }
  2533. }
  2534. break;
  2535. case 'year':
  2536. $current = intval(date('Y'));
  2537. $min = !isset($options['min']) ? $current - 20 : (int)$options['min'];
  2538. $max = !isset($options['max']) ? $current + 20 : (int)$options['max'];
  2539. if ($min > $max) {
  2540. list($min, $max) = array($max, $min);
  2541. }
  2542. if (!empty($options['value']) && (int)$options['value'] < $min) {
  2543. $min = (int)$options['value'];
  2544. } elseif (!empty($options['value']) && (int)$options['value'] > $max) {
  2545. $max = (int)$options['value'];
  2546. }
  2547. for ($i = $min; $i <= $max; $i++) {
  2548. $data[$i] = $i;
  2549. }
  2550. if ($options['order'] !== 'asc') {
  2551. $data = array_reverse($data, true);
  2552. }
  2553. break;
  2554. }
  2555. $this->_options[$name] = $data;
  2556. return $this->_options[$name];
  2557. }
  2558. /**
  2559. * Sets field defaults and adds field to form security input hash.
  2560. * Will also add a 'form-error' class if the field contains validation errors.
  2561. *
  2562. * ### Options
  2563. *
  2564. * - `secure` - boolean whether or not the field should be added to the security fields.
  2565. * Disabling the field using the `disabled` option, will also omit the field from being
  2566. * part of the hashed key.
  2567. *
  2568. * This method will convert a numerically indexed 'disabled' into a associative
  2569. * value. FormHelper's internals expect associative options.
  2570. *
  2571. * @param string $field Name of the field to initialize options for.
  2572. * @param array $options Array of options to append options into.
  2573. * @return array Array of options for the input.
  2574. */
  2575. protected function _initInputField($field, $options = array()) {
  2576. if (isset($options['secure'])) {
  2577. $secure = $options['secure'];
  2578. unset($options['secure']);
  2579. } else {
  2580. $secure = (isset($this->request['_Token']) && !empty($this->request['_Token']));
  2581. }
  2582. $disabledIndex = array_search('disabled', $options, true);
  2583. if ($disabledIndex !== false) {
  2584. unset($options[$disabledIndex]);
  2585. $options['disabled'] = true;
  2586. }
  2587. $result = parent::_initInputField($field, $options);
  2588. if ($this->tagIsInvalid() !== false) {
  2589. $result = $this->addClass($result, 'form-error');
  2590. }
  2591. if (!empty($result['disabled']) || $secure === self::SECURE_SKIP) {
  2592. return $result;
  2593. }
  2594. if (!isset($result['required']) &&
  2595. $this->_introspectModel($this->model(), 'validates', $this->field())
  2596. ) {
  2597. $result['required'] = true;
  2598. }
  2599. $fieldName = null;
  2600. if (!empty($options['name'])) {
  2601. preg_match_all('/\[(.*?)\]/', $options['name'], $matches);
  2602. if (isset($matches[1])) {
  2603. $fieldName = $matches[1];
  2604. }
  2605. }
  2606. $this->_secure($secure, $fieldName);
  2607. return $result;
  2608. }
  2609. /**
  2610. * Set/Get inputDefaults for form elements
  2611. *
  2612. * @param array $defaults New default values
  2613. * @param boolean Merge with current defaults
  2614. * @return array inputDefaults
  2615. */
  2616. public function inputDefaults($defaults = null, $merge = false) {
  2617. if (!is_null($defaults)) {
  2618. if ($merge) {
  2619. $this->_inputDefaults = array_merge($this->_inputDefaults, (array)$defaults);
  2620. } else {
  2621. $this->_inputDefaults = (array)$defaults;
  2622. }
  2623. }
  2624. return $this->_inputDefaults;
  2625. }
  2626. }