PageRenderTime 68ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

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

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