PageRenderTime 65ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/pyroka/hms
PHP | 2604 lines | 1971 code | 136 blank | 497 comment | 236 complexity | 55860a7758ac303540fd475aa3615d9e MD5 | raw file
Possible License(s): LGPL-2.1

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

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