PageRenderTime 63ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

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

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