PageRenderTime 65ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/Vendor/pear-pear.cakephp.org/CakePHP/Cake/View/Helper/FormHelper.php

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