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

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

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

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