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

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

https://bitbucket.org/npitts/easyuat2.0
PHP | 2593 lines | 1961 code | 137 blank | 495 comment | 244 complexity | 75c380653f7ff78f49c1944718d86149 MD5 | raw file

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

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