PageRenderTime 69ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

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

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