PageRenderTime 74ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

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

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