PageRenderTime 67ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/daveschwan/ronin-group
PHP | 2941 lines | 1847 code | 245 blank | 849 comment | 420 complexity | 53e99a625a11c876b1c52d5ad89e9c14 MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception, MIT, BSD-3-Clause, Apache-2.0

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

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