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

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

https://github.com/baidushine/cakephp
PHP | 2861 lines | 2158 code | 151 blank | 552 comment | 245 complexity | cf8d6520067166e8fe274a456deb56b8 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @package Cake.View.Helper
  13. * @since CakePHP(tm) v 0.10.0.1076
  14. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  15. */
  16. App::uses('ClassRegistry', 'Utility');
  17. App::uses('AppHelper', 'View/Helper');
  18. App::uses('Hash', 'Utility');
  19. /**
  20. * Form helper library.
  21. *
  22. * Automatic generation of HTML FORMs from given data.
  23. *
  24. * @package Cake.View.Helper
  25. * @property HtmlHelper $Html
  26. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html
  27. */
  28. class FormHelper extends AppHelper {
  29. /**
  30. * Other helpers used by FormHelper
  31. *
  32. * @var array
  33. */
  34. public $helpers = array('Html');
  35. /**
  36. * Options used by DateTime fields
  37. *
  38. * @var array
  39. */
  40. protected $_options = array(
  41. 'day' => array(), 'minute' => array(), 'hour' => array(),
  42. 'month' => array(), 'year' => array(), 'meridian' => array()
  43. );
  44. /**
  45. * List of fields created, used with secure forms.
  46. *
  47. * @var array
  48. */
  49. public $fields = array();
  50. /**
  51. * Constant used internally to skip the securing process,
  52. * and neither add the field to the hash or to the unlocked fields.
  53. *
  54. * @var string
  55. */
  56. const SECURE_SKIP = 'skip';
  57. /**
  58. * Defines the type of form being created. Set by FormHelper::create().
  59. *
  60. * @var string
  61. */
  62. public $requestType = null;
  63. /**
  64. * The default model being used for the current form.
  65. *
  66. * @var string
  67. */
  68. public $defaultModel = null;
  69. /**
  70. * Persistent default options used by input(). Set by FormHelper::create().
  71. *
  72. * @var array
  73. */
  74. protected $_inputDefaults = array();
  75. /**
  76. * An array of field names that have been excluded from
  77. * the Token hash used by SecurityComponent's validatePost method
  78. *
  79. * @see FormHelper::_secure()
  80. * @see SecurityComponent::validatePost()
  81. * @var array
  82. */
  83. protected $_unlockedFields = array();
  84. /**
  85. * Holds the model references already loaded by this helper
  86. * product of trying to inspect them out of field names
  87. *
  88. * @var array
  89. */
  90. protected $_models = array();
  91. /**
  92. * Holds all the validation errors for models loaded and inspected
  93. * it can also be set manually to be able to display custom error messages
  94. * in the any of the input fields generated by this helper
  95. *
  96. * @var array
  97. */
  98. public $validationErrors = array();
  99. /**
  100. * Copies the validationErrors variable from the View object into this instance
  101. *
  102. * @param View $View The View this helper is being attached to.
  103. * @param array $settings Configuration settings for the helper.
  104. */
  105. public function __construct(View $View, $settings = array()) {
  106. parent::__construct($View, $settings);
  107. $this->validationErrors =& $View->validationErrors;
  108. }
  109. /**
  110. * Guess the location for a model based on its name and tries to create a new instance
  111. * or get an already created instance of the model
  112. *
  113. * @param string $model
  114. * @return Model model instance
  115. */
  116. protected function _getModel($model) {
  117. $object = null;
  118. if (!$model || $model === 'Model') {
  119. return $object;
  120. }
  121. if (array_key_exists($model, $this->_models)) {
  122. return $this->_models[$model];
  123. }
  124. if (ClassRegistry::isKeySet($model)) {
  125. $object = ClassRegistry::getObject($model);
  126. } elseif (isset($this->request->params['models'][$model])) {
  127. $plugin = $this->request->params['models'][$model]['plugin'];
  128. $plugin .= ($plugin) ? '.' : null;
  129. $object = ClassRegistry::init(array(
  130. 'class' => $plugin . $this->request->params['models'][$model]['className'],
  131. 'alias' => $model
  132. ));
  133. } elseif (ClassRegistry::isKeySet($this->defaultModel)) {
  134. $defaultObject = ClassRegistry::getObject($this->defaultModel);
  135. if ($defaultObject && in_array($model, array_keys($defaultObject->getAssociated()), true) && isset($defaultObject->{$model})) {
  136. $object = $defaultObject->{$model};
  137. }
  138. } else {
  139. $object = ClassRegistry::init($model, true);
  140. }
  141. $this->_models[$model] = $object;
  142. if (!$object) {
  143. return null;
  144. }
  145. $this->fieldset[$model] = array('fields' => null, 'key' => $object->primaryKey, 'validates' => null);
  146. return $object;
  147. }
  148. /**
  149. * Inspects the model properties to extract information from them.
  150. * Currently it can extract information from the the fields, the primary key and required fields
  151. *
  152. * The $key parameter accepts the following list of values:
  153. *
  154. * - key: Returns the name of the primary key for the model
  155. * - fields: Returns the model schema
  156. * - validates: returns the list of fields that are required
  157. * - errors: returns the list of validation errors
  158. *
  159. * If the $field parameter is passed if will return the information for that sole field.
  160. *
  161. * `$this->_introspectModel('Post', 'fields', 'title');` will return the schema information for title column
  162. *
  163. * @param string $model name of the model to extract information from
  164. * @param string $key name of the special information key to obtain (key, fields, validates, errors)
  165. * @param string $field name of the model field to get information from
  166. * @return mixed information extracted for the special key and field in a model
  167. */
  168. protected function _introspectModel($model, $key, $field = null) {
  169. $object = $this->_getModel($model);
  170. if (!$object) {
  171. return;
  172. }
  173. if ($key === 'key') {
  174. return $this->fieldset[$model]['key'] = $object->primaryKey;
  175. }
  176. if ($key === 'fields') {
  177. if (!isset($this->fieldset[$model]['fields'])) {
  178. $this->fieldset[$model]['fields'] = $object->schema();
  179. foreach ($object->hasAndBelongsToMany as $alias => $assocData) {
  180. $this->fieldset[$object->alias]['fields'][$alias] = array('type' => 'multiple');
  181. }
  182. }
  183. if ($field === null || $field === false) {
  184. return $this->fieldset[$model]['fields'];
  185. } elseif (isset($this->fieldset[$model]['fields'][$field])) {
  186. return $this->fieldset[$model]['fields'][$field];
  187. } else {
  188. return isset($object->hasAndBelongsToMany[$field]) ? array('type' => 'multiple') : null;
  189. }
  190. }
  191. if ($key === 'errors' && !isset($this->validationErrors[$model])) {
  192. $this->validationErrors[$model] =& $object->validationErrors;
  193. return $this->validationErrors[$model];
  194. } elseif ($key === 'errors' && isset($this->validationErrors[$model])) {
  195. return $this->validationErrors[$model];
  196. }
  197. if ($key === 'validates' && !isset($this->fieldset[$model]['validates'])) {
  198. $validates = array();
  199. if (!empty($object->validate)) {
  200. foreach ($object->validator() as $validateField => $validateProperties) {
  201. if ($this->_isRequiredField($validateProperties)) {
  202. $validates[$validateField] = true;
  203. }
  204. }
  205. }
  206. $this->fieldset[$model]['validates'] = $validates;
  207. }
  208. if ($key === 'validates') {
  209. if (empty($field)) {
  210. return $this->fieldset[$model]['validates'];
  211. } else {
  212. return isset($this->fieldset[$model]['validates'][$field]) ?
  213. $this->fieldset[$model]['validates'] : null;
  214. }
  215. }
  216. }
  217. /**
  218. * Returns if a field is required to be filled based on validation properties from the validating object.
  219. *
  220. * @param CakeValidationSet $validationRules
  221. * @return boolean true if field is required to be filled, false otherwise
  222. */
  223. protected function _isRequiredField($validationRules) {
  224. if (empty($validationRules) || count($validationRules) === 0) {
  225. return false;
  226. }
  227. $isUpdate = $this->requestType === 'put';
  228. foreach ($validationRules as $rule) {
  229. $rule->isUpdate($isUpdate);
  230. if ($rule->skip()) {
  231. continue;
  232. }
  233. return !$rule->allowEmpty;
  234. }
  235. return false;
  236. }
  237. /**
  238. * Returns false if given form field described by the current entity has no errors.
  239. * Otherwise it returns the validation message
  240. *
  241. * @return mixed Either false when there are no errors, or an array of error
  242. * strings. An error string could be ''.
  243. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::tagIsInvalid
  244. */
  245. public function tagIsInvalid() {
  246. $entity = $this->entity();
  247. $model = array_shift($entity);
  248. $errors = array();
  249. if (!empty($entity) && isset($this->validationErrors[$model])) {
  250. $errors = $this->validationErrors[$model];
  251. }
  252. if (!empty($entity) && empty($errors)) {
  253. $errors = $this->_introspectModel($model, 'errors');
  254. }
  255. if (empty($errors)) {
  256. return false;
  257. }
  258. $errors = Hash::get($errors, implode('.', $entity));
  259. return $errors === null ? false : $errors;
  260. }
  261. /**
  262. * Returns an HTML FORM element.
  263. *
  264. * ### Options:
  265. *
  266. * - `type` Form method defaults to POST
  267. * - `action` The controller action the form submits to, (optional).
  268. * - `url` The url the form submits to. Can be a string or a url array. If you use 'url'
  269. * you should leave 'action' undefined.
  270. * - `default` Allows for the creation of Ajax forms. Set this to false to prevent the default event handler.
  271. * Will create an onsubmit attribute if it doesn't not exist. If it does, default action suppression
  272. * will be appended.
  273. * - `onsubmit` Used in conjunction with 'default' to create ajax forms.
  274. * - `inputDefaults` set the default $options for FormHelper::input(). Any options that would
  275. * be set when using FormHelper::input() can be set here. Options set with `inputDefaults`
  276. * can be overridden when calling input()
  277. * - `encoding` Set the accept-charset encoding for the form. Defaults to `Configure::read('App.encoding')`
  278. *
  279. * @param mixed $model The model name for which the form is being defined. Should
  280. * include the plugin name for plugin models. e.g. `ContactManager.Contact`.
  281. * If an array is passed and $options argument is empty, the array will be used as options.
  282. * If `false` no model is used.
  283. * @param array $options An array of html attributes and options.
  284. * @return string An formatted opening FORM tag.
  285. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-create
  286. */
  287. public function create($model = null, $options = array()) {
  288. $created = $id = false;
  289. $append = '';
  290. if (is_array($model) && empty($options)) {
  291. $options = $model;
  292. $model = null;
  293. }
  294. if (empty($model) && $model !== false && !empty($this->request->params['models'])) {
  295. $model = key($this->request->params['models']);
  296. } elseif (empty($model) && empty($this->request->params['models'])) {
  297. $model = false;
  298. }
  299. $this->defaultModel = $model;
  300. $key = null;
  301. if ($model !== false) {
  302. list($plugin, $model) = pluginSplit($model, true);
  303. $key = $this->_introspectModel($plugin . $model, 'key');
  304. $this->setEntity($model, true);
  305. }
  306. if ($model !== false && $key) {
  307. $recordExists = (
  308. isset($this->request->data[$model]) &&
  309. !empty($this->request->data[$model][$key]) &&
  310. !is_array($this->request->data[$model][$key])
  311. );
  312. if ($recordExists) {
  313. $created = true;
  314. $id = $this->request->data[$model][$key];
  315. }
  316. }
  317. $options = array_merge(array(
  318. 'type' => ($created && empty($options['action'])) ? 'put' : 'post',
  319. 'action' => null,
  320. 'url' => null,
  321. 'default' => true,
  322. 'encoding' => strtolower(Configure::read('App.encoding')),
  323. 'inputDefaults' => array()),
  324. $options);
  325. $this->inputDefaults($options['inputDefaults']);
  326. unset($options['inputDefaults']);
  327. if (!isset($options['id'])) {
  328. $domId = isset($options['action']) ? $options['action'] : $this->request['action'];
  329. $options['id'] = $this->domId($domId . 'Form');
  330. }
  331. if ($options['action'] === null && $options['url'] === null) {
  332. $options['action'] = $this->request->here(false);
  333. } elseif (empty($options['url']) || is_array($options['url'])) {
  334. if (empty($options['url']['controller'])) {
  335. if (!empty($model)) {
  336. $options['url']['controller'] = Inflector::underscore(Inflector::pluralize($model));
  337. } elseif (!empty($this->request->params['controller'])) {
  338. $options['url']['controller'] = Inflector::underscore($this->request->params['controller']);
  339. }
  340. }
  341. if (empty($options['action'])) {
  342. $options['action'] = $this->request->params['action'];
  343. }
  344. $plugin = null;
  345. if ($this->plugin) {
  346. $plugin = Inflector::underscore($this->plugin);
  347. }
  348. $actionDefaults = array(
  349. 'plugin' => $plugin,
  350. 'controller' => $this->_View->viewPath,
  351. 'action' => $options['action'],
  352. );
  353. $options['action'] = array_merge($actionDefaults, (array)$options['url']);
  354. if (empty($options['action'][0]) && !empty($id)) {
  355. $options['action'][0] = $id;
  356. }
  357. } elseif (is_string($options['url'])) {
  358. $options['action'] = $options['url'];
  359. }
  360. unset($options['url']);
  361. switch (strtolower($options['type'])) {
  362. case 'get':
  363. $htmlAttributes['method'] = 'get';
  364. break;
  365. case 'file':
  366. $htmlAttributes['enctype'] = 'multipart/form-data';
  367. $options['type'] = ($created) ? 'put' : 'post';
  368. case 'post':
  369. case 'put':
  370. case 'delete':
  371. $append .= $this->hidden('_method', array(
  372. 'name' => '_method', 'value' => strtoupper($options['type']), 'id' => null,
  373. 'secure' => self::SECURE_SKIP
  374. ));
  375. default:
  376. $htmlAttributes['method'] = 'post';
  377. break;
  378. }
  379. $this->requestType = strtolower($options['type']);
  380. $action = $this->url($options['action']);
  381. unset($options['type'], $options['action']);
  382. if (!$options['default']) {
  383. if (!isset($options['onsubmit'])) {
  384. $options['onsubmit'] = '';
  385. }
  386. $htmlAttributes['onsubmit'] = $options['onsubmit'] . 'event.returnValue = false; return false;';
  387. }
  388. unset($options['default']);
  389. if (!empty($options['encoding'])) {
  390. $htmlAttributes['accept-charset'] = $options['encoding'];
  391. unset($options['encoding']);
  392. }
  393. $htmlAttributes = array_merge($options, $htmlAttributes);
  394. $this->fields = array();
  395. if ($this->requestType !== 'get') {
  396. $append .= $this->_csrfField();
  397. }
  398. if (!empty($append)) {
  399. $append = $this->Html->useTag('hiddenblock', $append);
  400. }
  401. if ($model !== false) {
  402. $this->setEntity($model, true);
  403. $this->_introspectModel($model, 'fields');
  404. }
  405. return $this->Html->useTag('form', $action, $htmlAttributes) . $append;
  406. }
  407. /**
  408. * Return a CSRF input if the _Token is present.
  409. * Used to secure forms in conjunction with SecurityComponent
  410. *
  411. * @return string
  412. */
  413. protected function _csrfField() {
  414. if (empty($this->request->params['_Token'])) {
  415. return '';
  416. }
  417. if (!empty($this->request['_Token']['unlockedFields'])) {
  418. foreach ((array)$this->request['_Token']['unlockedFields'] as $unlocked) {
  419. $this->_unlockedFields[] = $unlocked;
  420. }
  421. }
  422. return $this->hidden('_Token.key', array(
  423. 'value' => $this->request->params['_Token']['key'], 'id' => 'Token' . mt_rand(),
  424. 'secure' => self::SECURE_SKIP
  425. ));
  426. }
  427. /**
  428. * Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden
  429. * input fields where appropriate.
  430. *
  431. * If $options is set a form submit button will be created. Options can be either a string or an array.
  432. *
  433. * {{{
  434. * array usage:
  435. *
  436. * array('label' => 'save'); value="save"
  437. * array('label' => 'save', 'name' => 'Whatever'); value="save" name="Whatever"
  438. * array('name' => 'Whatever'); value="Submit" name="Whatever"
  439. * array('label' => 'save', 'name' => 'Whatever', 'div' => 'good') <div class="good"> value="save" name="Whatever"
  440. * array('label' => 'save', 'name' => 'Whatever', 'div' => array('class' => 'good')); <div class="good"> value="save" name="Whatever"
  441. * }}}
  442. *
  443. * @param string|array $options as a string will use $options as the value of button,
  444. * @return string a closing FORM tag optional submit button.
  445. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#closing-the-form
  446. */
  447. public function end($options = null) {
  448. $out = null;
  449. $submit = null;
  450. if ($options !== null) {
  451. $submitOptions = array();
  452. if (is_string($options)) {
  453. $submit = $options;
  454. } else {
  455. if (isset($options['label'])) {
  456. $submit = $options['label'];
  457. unset($options['label']);
  458. }
  459. $submitOptions = $options;
  460. }
  461. $out .= $this->submit($submit, $submitOptions);
  462. }
  463. if (
  464. $this->requestType !== 'get' &&
  465. isset($this->request['_Token']) &&
  466. !empty($this->request['_Token'])
  467. ) {
  468. $out .= $this->secure($this->fields);
  469. $this->fields = array();
  470. }
  471. $this->setEntity(null);
  472. $out .= $this->Html->useTag('formend');
  473. $this->_View->modelScope = false;
  474. return $out;
  475. }
  476. /**
  477. * Generates a hidden field with a security hash based on the fields used in the form.
  478. *
  479. * @param array $fields The list of fields to use when generating the hash
  480. * @return string A hidden input field with a security hash
  481. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::secure
  482. */
  483. public function secure($fields = array()) {
  484. if (!isset($this->request['_Token']) || empty($this->request['_Token'])) {
  485. return;
  486. }
  487. $locked = array();
  488. $unlockedFields = $this->_unlockedFields;
  489. foreach ($fields as $key => $value) {
  490. if (!is_int($key)) {
  491. $locked[$key] = $value;
  492. unset($fields[$key]);
  493. }
  494. }
  495. sort($unlockedFields, SORT_STRING);
  496. sort($fields, SORT_STRING);
  497. ksort($locked, SORT_STRING);
  498. $fields += $locked;
  499. $locked = implode(array_keys($locked), '|');
  500. $unlocked = implode($unlockedFields, '|');
  501. $fields = Security::hash(serialize($fields) . $unlocked . Configure::read('Security.salt'), 'sha1');
  502. $out = $this->hidden('_Token.fields', array(
  503. 'value' => urlencode($fields . ':' . $locked),
  504. 'id' => 'TokenFields' . mt_rand()
  505. ));
  506. $out .= $this->hidden('_Token.unlocked', array(
  507. 'value' => urlencode($unlocked),
  508. 'id' => 'TokenUnlocked' . mt_rand()
  509. ));
  510. return $this->Html->useTag('hiddenblock', $out);
  511. }
  512. /**
  513. * Add to or get the list of fields that are currently unlocked.
  514. * Unlocked fields are not included in the field hash used by SecurityComponent
  515. * unlocking a field once its been added to the list of secured fields will remove
  516. * it from the list of fields.
  517. *
  518. * @param string $name The dot separated name for the field.
  519. * @return mixed Either null, or the list of fields.
  520. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::unlockField
  521. */
  522. public function unlockField($name = null) {
  523. if ($name === null) {
  524. return $this->_unlockedFields;
  525. }
  526. if (!in_array($name, $this->_unlockedFields)) {
  527. $this->_unlockedFields[] = $name;
  528. }
  529. $index = array_search($name, $this->fields);
  530. if ($index !== false) {
  531. unset($this->fields[$index]);
  532. }
  533. unset($this->fields[$name]);
  534. }
  535. /**
  536. * Determine which fields of a form should be used for hash.
  537. * Populates $this->fields
  538. *
  539. * @param boolean $lock Whether this field should be part of the validation
  540. * or excluded as part of the unlockedFields.
  541. * @param string|array $field Reference to field to be secured. Should be dot separated to indicate nesting.
  542. * @param mixed $value Field value, if value should not be tampered with.
  543. * @return void
  544. */
  545. protected function _secure($lock, $field = null, $value = null) {
  546. if (!$field) {
  547. $field = $this->entity();
  548. } elseif (is_string($field)) {
  549. $field = Hash::filter(explode('.', $field));
  550. }
  551. foreach ($this->_unlockedFields as $unlockField) {
  552. $unlockParts = explode('.', $unlockField);
  553. if (array_values(array_intersect($field, $unlockParts)) === $unlockParts) {
  554. return;
  555. }
  556. }
  557. $field = implode('.', $field);
  558. $field = preg_replace('/(\.\d+)+$/', '', $field);
  559. if ($lock) {
  560. if (!in_array($field, $this->fields)) {
  561. if ($value !== null) {
  562. return $this->fields[$field] = $value;
  563. }
  564. $this->fields[] = $field;
  565. }
  566. } else {
  567. $this->unlockField($field);
  568. }
  569. }
  570. /**
  571. * Returns true if there is an error for the given field, otherwise false
  572. *
  573. * @param string $field This should be "Modelname.fieldname"
  574. * @return boolean If there are errors this method returns true, else false.
  575. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::isFieldError
  576. */
  577. public function isFieldError($field) {
  578. $this->setEntity($field);
  579. return (bool)$this->tagIsInvalid();
  580. }
  581. /**
  582. * Returns a formatted error message for given FORM field, NULL if no errors.
  583. *
  584. * ### Options:
  585. *
  586. * - `escape` bool Whether or not to html escape the contents of the error.
  587. * - `wrap` mixed Whether or not the error message should be wrapped in a div. If a
  588. * string, will be used as the HTML tag to use.
  589. * - `class` string The classname for the error message
  590. *
  591. * @param string $field A field name, like "Modelname.fieldname"
  592. * @param string|array $text Error message as string or array of messages.
  593. * If array contains `attributes` key it will be used as options for error container
  594. * @param array $options Rendering options for <div /> wrapper tag
  595. * @return string If there are errors this method returns an error message, otherwise null.
  596. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::error
  597. */
  598. public function error($field, $text = null, $options = array()) {
  599. $defaults = array('wrap' => true, 'class' => 'error-message', 'escape' => true);
  600. $options = array_merge($defaults, $options);
  601. $this->setEntity($field);
  602. $error = $this->tagIsInvalid();
  603. if ($error === false) {
  604. return null;
  605. }
  606. if (is_array($text)) {
  607. if (isset($text['attributes']) && is_array($text['attributes'])) {
  608. $options = array_merge($options, $text['attributes']);
  609. unset($text['attributes']);
  610. }
  611. $tmp = array();
  612. foreach ($error as &$e) {
  613. if (isset($text[$e])) {
  614. $tmp[] = $text[$e];
  615. } else {
  616. $tmp[] = $e;
  617. }
  618. }
  619. $text = $tmp;
  620. }
  621. if ($text !== null) {
  622. $error = $text;
  623. }
  624. if (is_array($error)) {
  625. foreach ($error as &$e) {
  626. if (is_numeric($e)) {
  627. $e = __d('cake', 'Error in field %s', Inflector::humanize($this->field()));
  628. }
  629. }
  630. }
  631. if ($options['escape']) {
  632. $error = h($error);
  633. unset($options['escape']);
  634. }
  635. if (is_array($error)) {
  636. if (count($error) > 1) {
  637. $listParams = array();
  638. if (isset($options['listOptions'])) {
  639. if (is_string($options['listOptions'])) {
  640. $listParams[] = $options['listOptions'];
  641. } else {
  642. if (isset($options['listOptions']['itemOptions'])) {
  643. $listParams[] = $options['listOptions']['itemOptions'];
  644. unset($options['listOptions']['itemOptions']);
  645. } else {
  646. $listParams[] = array();
  647. }
  648. if (isset($options['listOptions']['tag'])) {
  649. $listParams[] = $options['listOptions']['tag'];
  650. unset($options['listOptions']['tag']);
  651. }
  652. array_unshift($listParams, $options['listOptions']);
  653. }
  654. unset($options['listOptions']);
  655. }
  656. array_unshift($listParams, $error);
  657. $error = call_user_func_array(array($this->Html, 'nestedList'), $listParams);
  658. } else {
  659. $error = array_pop($error);
  660. }
  661. }
  662. if ($options['wrap']) {
  663. $tag = is_string($options['wrap']) ? $options['wrap'] : 'div';
  664. unset($options['wrap']);
  665. return $this->Html->tag($tag, $error, $options);
  666. } else {
  667. return $error;
  668. }
  669. }
  670. /**
  671. * Returns a formatted LABEL element for HTML FORMs. Will automatically generate
  672. * a `for` attribute if one is not provided.
  673. *
  674. * ### Options
  675. *
  676. * - `for` - Set the for attribute, if its not defined the for attribute
  677. * will be generated from the $fieldName parameter using
  678. * FormHelper::domId().
  679. *
  680. * Examples:
  681. *
  682. * The text and for attribute are generated off of the fieldname
  683. *
  684. * {{{
  685. * echo $this->Form->label('Post.published');
  686. * <label for="PostPublished">Published</label>
  687. * }}}
  688. *
  689. * Custom text:
  690. *
  691. * {{{
  692. * echo $this->Form->label('Post.published', 'Publish');
  693. * <label for="PostPublished">Publish</label>
  694. * }}}
  695. *
  696. * Custom class name:
  697. *
  698. * {{{
  699. * echo $this->Form->label('Post.published', 'Publish', 'required');
  700. * <label for="PostPublished" class="required">Publish</label>
  701. * }}}
  702. *
  703. * Custom attributes:
  704. *
  705. * {{{
  706. * echo $this->Form->label('Post.published', 'Publish', array(
  707. * 'for' => 'post-publish'
  708. * ));
  709. * <label for="post-publish">Publish</label>
  710. * }}}
  711. *
  712. * @param string $fieldName This should be "Modelname.fieldname"
  713. * @param string $text Text that will appear in the label field. If
  714. * $text is left undefined the text will be inflected from the
  715. * fieldName.
  716. * @param array|string $options An array of HTML attributes, or a string, to be used as a class name.
  717. * @return string The formatted LABEL element
  718. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::label
  719. */
  720. public function label($fieldName = null, $text = null, $options = array()) {
  721. if ($fieldName === null) {
  722. $fieldName = implode('.', $this->entity());
  723. }
  724. if ($text === null) {
  725. if (strpos($fieldName, '.') !== false) {
  726. $fieldElements = explode('.', $fieldName);
  727. $text = array_pop($fieldElements);
  728. } else {
  729. $text = $fieldName;
  730. }
  731. if (substr($text, -3) === '_id') {
  732. $text = substr($text, 0, -3);
  733. }
  734. $text = __(Inflector::humanize(Inflector::underscore($text)));
  735. }
  736. if (is_string($options)) {
  737. $options = array('class' => $options);
  738. }
  739. if (isset($options['for'])) {
  740. $labelFor = $options['for'];
  741. unset($options['for']);
  742. } else {
  743. $labelFor = $this->domId($fieldName);
  744. }
  745. return $this->Html->useTag('label', $labelFor, $options, $text);
  746. }
  747. /**
  748. * Generate a set of inputs for `$fields`. If $fields is null the fields of current model
  749. * will be used.
  750. *
  751. * You can customize individual inputs through `$fields`.
  752. * {{{
  753. * $this->Form->inputs(array(
  754. * 'name' => array('label' => 'custom label')
  755. * ));
  756. * }}}
  757. *
  758. * In addition to controller fields output, `$fields` can be used to control legend
  759. * and fieldset rendering.
  760. * `$this->Form->inputs('My legend');` Would generate an input set with a custom legend.
  761. * Passing `fieldset` and `legend` key in `$fields` array has been deprecated since 2.3,
  762. * for more fine grained control use the `fieldset` and `legend` keys in `$options` param.
  763. *
  764. * @param array $fields An array of fields to generate inputs for, or null.
  765. * @param array $blacklist A simple array of fields to not create inputs for.
  766. * @param array $options Options array. Valid keys are:
  767. * - `fieldset` Set to false to disable the fieldset. If a string is supplied it will be used as
  768. * the classname for the fieldset element.
  769. * - `legend` Set to false to disable the legend for the generated input set. Or supply a string
  770. * to customize the legend text.
  771. * @return string Completed form inputs.
  772. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::inputs
  773. */
  774. public function inputs($fields = null, $blacklist = null, $options = array()) {
  775. $fieldset = $legend = true;
  776. $modelFields = array();
  777. $model = $this->model();
  778. if ($model) {
  779. $modelFields = array_keys((array)$this->_introspectModel($model, 'fields'));
  780. }
  781. if (is_array($fields)) {
  782. if (array_key_exists('legend', $fields) && !in_array('legend', $modelFields)) {
  783. $legend = $fields['legend'];
  784. unset($fields['legend']);
  785. }
  786. if (isset($fields['fieldset']) && !in_array('fieldset', $modelFields)) {
  787. $fieldset = $fields['fieldset'];
  788. unset($fields['fieldset']);
  789. }
  790. } elseif ($fields !== null) {
  791. $fieldset = $legend = $fields;
  792. if (!is_bool($fieldset)) {
  793. $fieldset = true;
  794. }
  795. $fields = array();
  796. }
  797. if (isset($options['legend'])) {
  798. $legend = $options['legend'];
  799. }
  800. if (isset($options['fieldset'])) {
  801. $fieldset = $options['fieldset'];
  802. }
  803. if (empty($fields)) {
  804. $fields = $modelFields;
  805. }
  806. if ($legend === true) {
  807. $actionName = __d('cake', 'New %s');
  808. $isEdit = (
  809. strpos($this->request->params['action'], 'update') !== false ||
  810. strpos($this->request->params['action'], 'edit') !== false
  811. );
  812. if ($isEdit) {
  813. $actionName = __d('cake', 'Edit %s');
  814. }
  815. $modelName = Inflector::humanize(Inflector::underscore($model));
  816. $legend = sprintf($actionName, __($modelName));
  817. }
  818. $out = null;
  819. foreach ($fields as $name => $options) {
  820. if (is_numeric($name) && !is_array($options)) {
  821. $name = $options;
  822. $options = array();
  823. }
  824. $entity = explode('.', $name);
  825. $blacklisted = (
  826. is_array($blacklist) &&
  827. (in_array($name, $blacklist) || in_array(end($entity), $blacklist))
  828. );
  829. if ($blacklisted) {
  830. continue;
  831. }
  832. $out .= $this->input($name, $options);
  833. }
  834. if (is_string($fieldset)) {
  835. $fieldsetClass = sprintf(' class="%s"', $fieldset);
  836. } else {
  837. $fieldsetClass = '';
  838. }
  839. if ($fieldset) {
  840. if ($legend) {
  841. $out = $this->Html->useTag('legend', $legend) . $out;
  842. }
  843. $out = $this->Html->useTag('fieldset', $fieldsetClass, $out);
  844. }
  845. return $out;
  846. }
  847. /**
  848. * Generates a form input element complete with label and wrapper div
  849. *
  850. * ### Options
  851. *
  852. * See each field type method for more information. Any options that are part of
  853. * $attributes or $options for the different **type** methods can be included in `$options` for input().i
  854. * Additionally, any unknown keys that are not in the list below, or part of the selected type's options
  855. * will be treated as a regular html attribute for the generated input.
  856. *
  857. * - `type` - Force the type of widget you want. e.g. `type => 'select'`
  858. * - `label` - Either a string label, or an array of options for the label. See FormHelper::label().
  859. * - `div` - Either `false` to disable the div, or an array of options for the div.
  860. * See HtmlHelper::div() for more options.
  861. * - `options` - For widgets that take options e.g. radio, select.
  862. * - `error` - Control the error message that is produced. Set to `false` to disable any kind of error reporting (field
  863. * error and error messages).
  864. * - `errorMessage` - Boolean to control rendering error messages (field error will still occur).
  865. * - `empty` - String or boolean to enable empty select box options.
  866. * - `before` - Content to place before the label + input.
  867. * - `after` - Content to place after the label + input.
  868. * - `between` - Content to place between the label + input.
  869. * - `format` - Format template for element order. Any element that is not in the array, will not be in the output.
  870. * - Default input format order: array('before', 'label', 'between', 'input', 'after', 'error')
  871. * - Default checkbox format order: array('before', 'input', 'between', 'label', 'after', 'error')
  872. * - Hidden input will not be formatted
  873. * - Radio buttons cannot have the order of input and label elements controlled with these settings.
  874. *
  875. * @param string $fieldName This should be "Modelname.fieldname"
  876. * @param array $options Each type of input takes different options.
  877. * @return string Completed form widget.
  878. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#creating-form-elements
  879. */
  880. public function input($fieldName, $options = array()) {
  881. $this->setEntity($fieldName);
  882. $options = $this->_parseOptions($options);
  883. $divOptions = $this->_divOptions($options);
  884. unset($options['div']);
  885. if ($options['type'] === 'radio' && isset($options['options'])) {
  886. $radioOptions = (array)$options['options'];
  887. unset($options['options']);
  888. }
  889. $label = $this->_getLabel($fieldName, $options);
  890. if ($options['type'] !== 'radio') {
  891. unset($options['label']);
  892. }
  893. $error = $this->_extractOption('error', $options, null);
  894. unset($options['error']);
  895. $errorMessage = $this->_extractOption('errorMessage', $options, true);
  896. unset($options['errorMessage']);
  897. $selected = $this->_extractOption('selected', $options, null);
  898. unset($options['selected']);
  899. if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time') {
  900. $dateFormat = $this->_extractOption('dateFormat', $options, 'MDY');
  901. $timeFormat = $this->_extractOption('timeFormat', $options, 12);
  902. unset($options['dateFormat'], $options['timeFormat']);
  903. }
  904. $type = $options['type'];
  905. $out = array('before' => $options['before'], 'label' => $label, 'between' => $options['between'], 'after' => $options['after']);
  906. $format = $this->_getFormat($options);
  907. unset($options['type'], $options['before'], $options['between'], $options['after'], $options['format']);
  908. $out['error'] = null;
  909. if ($type !== 'hidden' && $error !== false) {
  910. $errMsg = $this->error($fieldName, $error);
  911. if ($errMsg) {
  912. $divOptions = $this->addClass($divOptions, 'error');
  913. if ($errorMessage) {
  914. $out['error'] = $errMsg;
  915. }
  916. }
  917. }
  918. if ($type === 'radio' && isset($out['between'])) {
  919. $options['between'] = $out['between'];
  920. $out['between'] = null;
  921. }
  922. $out['input'] = $this->_getInput(compact('type', 'fieldName', 'options', 'radioOptions', 'selected', 'dateFormat', 'timeFormat'));
  923. $output = '';
  924. foreach ($format as $element) {
  925. $output .= $out[$element];
  926. }
  927. if (!empty($divOptions['tag'])) {
  928. $tag = $divOptions['tag'];
  929. unset($divOptions['tag']);
  930. $output = $this->Html->tag($tag, $output, $divOptions);
  931. }
  932. return $output;
  933. }
  934. /**
  935. * Generates an input element
  936. *
  937. * @param type $args
  938. * @return type
  939. */
  940. protected function _getInput($args) {
  941. extract($args);
  942. switch ($type) {
  943. case 'hidden':
  944. return $this->hidden($fieldName, $options);
  945. case 'checkbox':
  946. return $this->checkbox($fieldName, $options);
  947. case 'radio':
  948. return $this->radio($fieldName, $radioOptions, $options);
  949. case 'file':
  950. return $this->file($fieldName, $options);
  951. case 'select':
  952. $options += array('options' => array(), 'value' => $selected);
  953. $list = $options['options'];
  954. unset($options['options']);
  955. return $this->select($fieldName, $list, $options);
  956. case 'time':
  957. $options['value'] = $selected;
  958. return $this->dateTime($fieldName, null, $timeFormat, $options);
  959. case 'date':
  960. $options['value'] = $selected;
  961. return $this->dateTime($fieldName, $dateFormat, null, $options);
  962. case 'datetime':
  963. $options['value'] = $selected;
  964. return $this->dateTime($fieldName, $dateFormat, $timeFormat, $options);
  965. case 'textarea':
  966. return $this->textarea($fieldName, $options + array('cols' => '30', 'rows' => '6'));
  967. case 'url':
  968. return $this->text($fieldName, array('type' => 'url') + $options);
  969. default:
  970. return $this->{$type}($fieldName, $options);
  971. }
  972. }
  973. /**
  974. * Generates input options array
  975. *
  976. * @param type $options
  977. * @return array Options
  978. */
  979. protected function _parseOptions($options) {
  980. $options = array_merge(
  981. array('before' => null, 'between' => null, 'after' => null, 'format' => null),
  982. $this->_inputDefaults,
  983. $options
  984. );
  985. if (!isset($options['type'])) {
  986. $options = $this->_magicOptions($options);
  987. }
  988. if (in_array($options['type'], array('checkbox', 'radio', 'select'))) {
  989. $options = $this->_optionsOptions($options);
  990. }
  991. if (isset($options['rows']) || isset($options['cols'])) {
  992. $options['type'] = 'textarea';
  993. }
  994. if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time' || $options['type'] === 'select') {
  995. $options += array('empty' => false);
  996. }
  997. return $options;
  998. }
  999. /**
  1000. * Generates list of options for multiple select
  1001. *
  1002. * @param type $options
  1003. * @return array
  1004. */
  1005. protected function _optionsOptions($options) {
  1006. if (isset($options['options'])) {
  1007. return $options;
  1008. }
  1009. $varName = Inflector::variable(
  1010. Inflector::pluralize(preg_replace('/_id$/', '', $this->field()))
  1011. );
  1012. $varOptions = $this->_View->getVar($varName);
  1013. if (!is_array($varOptions)) {
  1014. return $options;
  1015. }
  1016. if ($options['type'] !== 'radio') {
  1017. $options['type'] = 'select';
  1018. }
  1019. $options['options'] = $varOptions;
  1020. return $options;
  1021. }
  1022. /**
  1023. * Magically set option type and corresponding options
  1024. *
  1025. * @param type $options
  1026. * @return array
  1027. */
  1028. protected function _magicOptions($options) {
  1029. $modelKey = $this->model();
  1030. $fieldKey = $this->field();
  1031. $options['type'] = 'text';
  1032. if (isset($options['options'])) {
  1033. $options['type'] = 'select';
  1034. } elseif (in_array($fieldKey, array('psword', 'passwd', 'password'))) {
  1035. $options['type'] = 'password';
  1036. } elseif (in_array($fieldKey, array('tel', 'telephone', 'phone'))) {
  1037. $options['type'] = 'tel';
  1038. } elseif ($fieldKey === 'email') {
  1039. $options['type'] = 'email';
  1040. } elseif (isset($options['checked'])) {
  1041. $options['type'] = 'checkbox';
  1042. } elseif ($fieldDef = $this->_introspectModel($modelKey, 'fields', $fieldKey)) {
  1043. $type = $fieldDef['type'];
  1044. $primaryKey = $this->fieldset[$modelKey]['key'];
  1045. $map = array(
  1046. 'string' => 'text', 'datetime' => 'datetime',
  1047. 'boolean' => 'checkbox', 'timestamp' => 'datetime',
  1048. 'text' => 'textarea', 'time' => 'time',
  1049. 'date' => 'date', 'float' => 'number',
  1050. 'integer' => 'number'
  1051. );
  1052. if (isset($this->map[$type])) {
  1053. $options['type'] = $this->map[$type];
  1054. } elseif (isset($map[$type])) {
  1055. $options['type'] = $map[$type];
  1056. }
  1057. if ($fieldKey == $primaryKey) {
  1058. $options['type'] = 'hidden';
  1059. }
  1060. if (
  1061. $options['type'] === 'number' &&
  1062. $type === 'float' &&
  1063. !isset($options['step'])
  1064. ) {
  1065. $options['step'] = 'any';
  1066. }
  1067. }
  1068. if (preg_match('/_id$/', $fieldKey) && $options['type'] !== 'hidden') {
  1069. $options['type'] = 'select';
  1070. }
  1071. if ($modelKey === $fieldKey) {
  1072. $options['type'] = 'select';
  1073. if (!isset($options['multiple'])) {
  1074. $options['multiple'] = 'multiple';
  1075. }
  1076. }
  1077. if (in_array($options['type'], array('text', 'number'))) {
  1078. $options = $this->_optionsOptions($options);
  1079. }
  1080. if ($options['type'] === 'select' && array_key_exists('step', $options)) {
  1081. unset($options['step']);
  1082. }
  1083. $options = $this->_maxLength($options);
  1084. return $options;
  1085. }
  1086. /**
  1087. * Generate format options
  1088. *
  1089. * @param type $options
  1090. * @return array
  1091. */
  1092. protected function _getFormat($options) {
  1093. if ($options['type'] === 'hidden') {
  1094. return array('input');
  1095. }
  1096. if (is_array($options['format']) && in_array('input', $options['format'])) {
  1097. return $options['format'];
  1098. }
  1099. if ($options['type'] === 'checkbox') {
  1100. return array('before', 'input', 'between', 'label', 'after', 'error');
  1101. }
  1102. return array('before', 'label', 'between', 'input', 'after', 'error');
  1103. }
  1104. /**
  1105. * Generate label for input
  1106. *
  1107. * @param type $fieldName
  1108. * @param type $options
  1109. * @return boolean|string false or Generated label element
  1110. */
  1111. protected function _getLabel($fieldName, $options) {
  1112. if ($options['type'] === 'radio') {
  1113. return false;
  1114. }
  1115. $label = null;
  1116. if (isset($options['label'])) {
  1117. $label = $options['label'];
  1118. }
  1119. if ($label === false) {
  1120. return false;
  1121. }
  1122. return $this->_inputLabel($fieldName, $label, $options);
  1123. }
  1124. /**
  1125. * Calculates maxlength option
  1126. *
  1127. * @param type $options
  1128. * @return array
  1129. */
  1130. protected function _maxLength($options) {
  1131. $fieldDef = $this->_introspectModel($this->model(), 'fields', $this->field());
  1132. $autoLength = (
  1133. !array_key_exists('maxlength', $options) &&
  1134. isset($fieldDef['length']) &&
  1135. is_scalar($fieldDef['length']) &&
  1136. $options['type'] !== 'select'
  1137. );
  1138. if ($autoLength &&
  1139. in_array($options['type'], array('text', 'email', 'tel', 'url', 'search'))
  1140. ) {
  1141. $options['maxlength'] = $fieldDef['length'];
  1142. }
  1143. return $options;
  1144. }
  1145. /**
  1146. * Generate div options for input
  1147. *
  1148. * @param array $options
  1149. * @return array
  1150. */
  1151. protected function _divOptions($options) {
  1152. if ($options['type'] === 'hidden') {
  1153. return array();
  1154. }
  1155. $div = $this->_extractOption('div', $options, true);
  1156. if (!$div) {
  1157. return array();
  1158. }
  1159. $divOptions = array('class' => 'input');
  1160. $divOptions = $this->addClass($divOptions, $options['type']);
  1161. if (is_string($div)) {
  1162. $divOptions['class'] = $div;
  1163. } elseif (is_array($div)) {
  1164. $divOptions = array_merge($divOptions, $div);
  1165. }
  1166. if ($this->_introspectModel($this->model(), 'validates', $this->field())) {
  1167. $divOptions = $this->addClass($divOptions, 'required');
  1168. }
  1169. if (!isset($divOptions['tag'])) {
  1170. $divOptions['tag'] = 'div';
  1171. }
  1172. return $divOptions;
  1173. }
  1174. /**
  1175. * Extracts a single option from an options array.
  1176. *
  1177. * @param string $name The name of the option to pull out.
  1178. * @param array $options The array of options you want to extract.
  1179. * @param mixed $default The default option value
  1180. * @return mixed the contents of the option or default
  1181. */
  1182. protected function _extractOption($name, $options, $default = null) {
  1183. if (array_key_exists($name, $options)) {
  1184. return $options[$name];
  1185. }
  1186. return $default;
  1187. }
  1188. /**
  1189. * Generate a label for an input() call.
  1190. *
  1191. * $options can contain a hash of id overrides. These overrides will be
  1192. * used instead of the generated values if present.
  1193. *
  1194. * @param string $fieldName
  1195. * @param string $label
  1196. * @param array $options Options for the label element.
  1197. * @return string Generated label element
  1198. * @deprecated 'NONE' option is deprecated and will be removed in 3.0
  1199. */
  1200. protected function _inputLabel($fieldName, $label, $options) {
  1201. $labelAttributes = $this->domId(array(), 'for');
  1202. $idKey = null;
  1203. if ($options['type'] === 'date' || $options['type'] === 'datetime') {
  1204. $firstInput = 'M';
  1205. if (
  1206. array_key_exists('dateFormat', $options) &&
  1207. ($options['dateFormat'] === null || $options['dateFormat'] === 'NONE')
  1208. ) {
  1209. $firstInput = 'H';
  1210. } elseif (!empty($options['dateFormat'])) {
  1211. $firstInput = substr($options['dateFormat'], 0, 1);
  1212. }
  1213. switch ($firstInput) {
  1214. case 'D':
  1215. $idKey = 'day';
  1216. $labelAttributes['for'] .= 'Day';
  1217. break;
  1218. case 'Y':
  1219. $idKey = 'year';
  1220. $labelAttributes['for'] .= 'Year';
  1221. break;
  1222. case 'M':
  1223. $idKey = 'month';
  1224. $labelAttributes['for'] .= 'Month';
  1225. break;
  1226. case 'H':
  1227. $idKey = 'hour';
  1228. $labelAttributes['for'] .= 'Hour';
  1229. }
  1230. }
  1231. if ($options['type'] === 'time') {
  1232. $labelAttributes['for'] .= 'Hour';
  1233. $idKey = 'hour';
  1234. }
  1235. if (isset($idKey) && isset($options['id']) && isset($options['id'][$idKey])) {
  1236. $labelAttributes['for'] = $options['id'][$idKey];
  1237. }
  1238. if (is_array($label)) {
  1239. $labelText = null;
  1240. if (isset($label['text'])) {
  1241. $labelText = $label['text'];
  1242. unset($label['text']);
  1243. }
  1244. $labelAttributes = array_merge($labelAttributes, $label);
  1245. } else {
  1246. $labelText = $label;
  1247. }
  1248. if (isset($options['id']) && is_string($options['id'])) {
  1249. $labelAttributes = array_merge($labelAttributes, array('for' => $options['id']));
  1250. }
  1251. return $this->label($fieldName, $labelText, $labelAttributes);
  1252. }
  1253. /**
  1254. * Creates a checkbox input widget.
  1255. *
  1256. * ### Options:
  1257. *
  1258. * - `value` - the value of the checkbox
  1259. * - `checked` - boolean indicate that this checkbox is checked.
  1260. * - `hiddenField` - boolean to indicate if you want the results of checkbox() to include
  1261. * a hidden input with a value of ''.
  1262. * - `disabled` - create a disabled input.
  1263. * - `default` - Set the default value for the checkbox. This allows you to start checkboxes
  1264. * as checked, without having to check the POST data. A matching POST data value, will overwrite
  1265. * the default value.
  1266. *
  1267. * @param string $fieldName Name of a field, like this "Modelname.fieldname"
  1268. * @param array $options Array of HTML attributes.
  1269. * @return string An HTML text input element.
  1270. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
  1271. */
  1272. public function checkbox($fieldName, $options = array()) {
  1273. $valueOptions = array();
  1274. if (isset($options['default'])) {
  1275. $valueOptions['default'] = $options['default'];
  1276. unset($options['default']);
  1277. }
  1278. $options += array('required' => false);
  1279. $options = $this->_initInputField($fieldName, $options) + array('hiddenField' => true);
  1280. $value = current($this->value($valueOptions));
  1281. $output = '';
  1282. if (empty($options['value'])) {
  1283. $options['value'] = 1;
  1284. }
  1285. if (
  1286. (!isset($options['checked']) && !empty($value) && $value == $options['value']) ||
  1287. !empty($options['checked'])
  1288. ) {
  1289. $options['checked'] = 'checked';
  1290. }
  1291. if ($options['hiddenField']) {
  1292. $hiddenOptions = array(
  1293. 'id' => $options['id'] . '_',
  1294. 'name' => $options['name'],
  1295. 'value' => ($options['hiddenField'] !== true ? $options['hiddenField'] : '0'),
  1296. 'secure' => false
  1297. );
  1298. if (isset($options['disabled']) && $options['disabled']) {
  1299. $hiddenOptions['disabled'] = 'disabled';
  1300. }
  1301. $output = $this->hidden($fieldName, $hiddenOptions);
  1302. }
  1303. unset($options['hiddenField']);
  1304. return $output . $this->Html->useTag('checkbox', $options['name'], array_diff_key($options, array('name' => null)));
  1305. }
  1306. /**
  1307. * Creates a set of radio widgets. Will create a legend and fieldset
  1308. * by default. Use $options to control this
  1309. *
  1310. * ### Attributes:
  1311. *
  1312. * - `separator` - define the string in between the radio buttons
  1313. * - `between` - the string between legend and input set or array of strings to insert
  1314. * strings between each input block
  1315. * - `legend` - control whether or not the widget set has a fieldset & legend
  1316. * - `value` - indicate a value that is should be checked
  1317. * - `label` - boolean to indicate whether or not labels for widgets show be displayed
  1318. * - `hiddenField` - boolean to indicate if you want the results of radio() to include
  1319. * a hidden input with a value of ''. This is useful for creating radio sets that non-continuous
  1320. * - `disabled` - Set to `true` or `disabled` to disable all the radio buttons.
  1321. * - `empty` - Set to `true` to create a input with the value '' as the first option. When `true`
  1322. * the radio label will be 'empty'. Set this option to a string to control the label value.
  1323. *
  1324. * @param string $fieldName Name of a field, like this "Modelname.fieldname"
  1325. * @param array $options Radio button options array.
  1326. * @param array $attributes Array of HTML attributes, and special attributes above.
  1327. * @return string Completed radio widget set.
  1328. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
  1329. */
  1330. public function radio($fieldName, $options = array(), $attributes = array()) {
  1331. $attributes = $this->_initInputField($fieldName, $attributes);
  1332. $showEmpty = $this->_extractOption('empty', $attributes);
  1333. if ($showEmpty) {
  1334. $showEmpty = ($showEmpty === true) ? __d('cake', 'empty') : $showEmpty;
  1335. $options = array('' => $showEmpty) + $options;
  1336. }
  1337. unset($attributes['empty']);
  1338. $legend = false;
  1339. if (isset($attributes['legend'])) {
  1340. $legend = $attributes['legend'];
  1341. unset($attributes['legend']);
  1342. } elseif (count($options) > 1) {
  1343. $legend = __(Inflector::humanize($this->field()));
  1344. }
  1345. $label = true;
  1346. if (isset($attributes['label'])) {
  1347. $label = $attributes['label'];
  1348. unset($attributes['label']);
  1349. }
  1350. $separator = null;
  1351. if (isset($attributes['separator'])) {
  1352. $separator = $attributes['separator'];
  1353. unset($attributes['separator']);
  1354. }
  1355. $between = null;
  1356. if (isset($attributes['between'])) {
  1357. $between = $attributes['between'];
  1358. unset($attributes['between']);
  1359. }
  1360. $value = null;
  1361. if (isset($attributes['value'])) {
  1362. $value = $attributes['value'];
  1363. } else {
  1364. $value = $this->value($fieldName);
  1365. }
  1366. $disabled = array();
  1367. if (isset($attributes['disabled'])) {
  1368. $disabled = $attributes['disabled'];
  1369. }
  1370. $out = array();
  1371. $hiddenField = isset($attributes['hiddenField']) ? $attributes['hiddenField'] : true;
  1372. unset($attributes['hiddenField']);
  1373. if (isset($value) && is_bool($value)) {
  1374. $value = $value ? 1 : 0;
  1375. }
  1376. foreach ($options as $optValue => $optTitle) {
  1377. $optionsHere = array('value' => $optValue);
  1378. if (isset($value) && strval($optValue) === strval($value)) {
  1379. $optionsHere['checked'] = 'checked';
  1380. }
  1381. $isNumeric = is_numeric($optValue);
  1382. if ($disabled && (!is_array($disabled) || in_array((string)$optValue, $disabled, !$isNumeric))) {
  1383. $optionsHere['disabled'] = true;
  1384. }
  1385. $tagName = Inflector::camelize(
  1386. $attributes['id'] . '_' . Inflector::slug($optValue)
  1387. );
  1388. if ($label) {
  1389. $optTitle = $this->Html->useTag('label', $tagName, '', $optTitle);
  1390. }
  1391. if (is_array($between)) {
  1392. $optTitle .= array_shift($between);
  1393. }
  1394. $allOptions = array_merge($attributes, $optionsHere);
  1395. $out[] = $this->Html->useTag('radio', $attributes['name'], $tagName,
  1396. array_diff_key($allOptions, array('name' => null, 'type' => null, 'id' => null)),
  1397. $optTitle
  1398. );
  1399. }
  1400. $hidden = null;
  1401. if ($hiddenField) {
  1402. if (!isset($value) || $value === '') {
  1403. $hidden = $this->hidden($fieldName, array(
  1404. 'id' => $attributes['id'] . '_', 'value' => '', 'name' => $attributes['name']
  1405. ));
  1406. }
  1407. }
  1408. $out = $hidden . implode($separator, $out);
  1409. if (is_array($between)) {
  1410. $between = '';
  1411. }
  1412. if ($legend) {
  1413. $out = $this->Html->useTag('fieldset', '', $this->Html->useTag('legend', $legend) . $between . $out);
  1414. }
  1415. return $out;
  1416. }
  1417. /**
  1418. * Missing method handler - implements various simple input types. Is used to create inputs
  1419. * of various types. e.g. `$this->Form->text();` will create `<input type="text" />` while
  1420. * `$this->Form->range();` will create `<input type="range" />`
  1421. *
  1422. * ### Usage
  1423. *
  1424. * `$this->Form->search('User.query', array('value' => 'test'));`
  1425. *
  1426. * Will make an input like:
  1427. *
  1428. * `<input type="search" id="UserQuery" name="data[User][query]" value="test" />`
  1429. *
  1430. * The first argument to an input type should always be the fieldname, in `Model.field` format.
  1431. * The second argument should always be an array of attributes for the input.
  1432. *
  1433. * @param string $method Method name / input type to make.
  1434. * @param array $params Parameters for the method call
  1435. * @return string Formatted input method.
  1436. * @throws CakeException When there are no params for the method call.
  1437. */
  1438. public function __call($method, $params) {
  1439. $options = array();
  1440. if (empty($params)) {
  1441. throw new CakeException(__d('cake_dev', 'Missing field name for FormHelper::%s', $method));
  1442. }
  1443. if (isset($params[1])) {
  1444. $options = $params[1];
  1445. }
  1446. if (!isset($options['type'])) {
  1447. $options['type'] = $method;
  1448. }
  1449. $options = $this->_initInputField($params[0], $options);
  1450. return $this->Html->useTag('input', $options['name'], array_diff_key($options, array('name' =>

Large files files are truncated, but you can click here to view the full file