PageRenderTime 62ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/udeshika/fake_twitter
PHP | 2556 lines | 1924 code | 137 blank | 495 comment | 243 complexity | 3e79601d32ac2ecbf0ff3d257d181fc7 MD5 | raw file

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

  1. <?php
  2. /**
  3. * Automatic generation of HTML FORMs from given data.
  4. *
  5. * Used for scaffolding.
  6. *
  7. * PHP 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package Cake.View.Helper
  18. * @since CakePHP(tm) v 0.10.0.1076
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. App::uses('AppHelper', 'View/Helper');
  22. /**
  23. * Form helper library.
  24. *
  25. * Automatic generation of HTML FORMs from given data.
  26. *
  27. * @package Cake.View.Helper
  28. * @property HtmlHelper $Html
  29. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html
  30. */
  31. class FormHelper extends AppHelper {
  32. /**
  33. * Other helpers used by FormHelper
  34. *
  35. * @var array
  36. */
  37. public $helpers = array('Html');
  38. /**
  39. * Options used by DateTime fields
  40. *
  41. * @var array
  42. */
  43. protected $_options = array(
  44. 'day' => array(), 'minute' => array(), 'hour' => array(),
  45. 'month' => array(), 'year' => array(), 'meridian' => array()
  46. );
  47. /**
  48. * List of fields created, used with secure forms.
  49. *
  50. * @var array
  51. */
  52. public $fields = array();
  53. /**
  54. * Constant used internally to skip the securing process,
  55. * and neither add the field to the hash or to the unlocked fields.
  56. *
  57. * @var string
  58. */
  59. const SECURE_SKIP = 'skip';
  60. /**
  61. * Defines the type of form being created. Set by FormHelper::create().
  62. *
  63. * @var string
  64. */
  65. public $requestType = null;
  66. /**
  67. * The default model being used for the current form.
  68. *
  69. * @var string
  70. */
  71. public $defaultModel = null;
  72. /**
  73. * Persistent default options used by input(). Set by FormHelper::create().
  74. *
  75. * @var array
  76. */
  77. protected $_inputDefaults = array();
  78. /**
  79. * An array of field names that have been excluded from
  80. * the Token hash used by SecurityComponent's validatePost method
  81. *
  82. * @see FormHelper::_secure()
  83. * @see SecurityComponent::validatePost()
  84. * @var array
  85. */
  86. protected $_unlockedFields = array();
  87. /**
  88. * Holds the model references already loaded by this helper
  89. * product of trying to inspect them out of field names
  90. *
  91. * @var array
  92. */
  93. protected $_models = array();
  94. /**
  95. * Holds all the validation errors for models loaded and inspected
  96. * it can also be set manually to be able to display custom error messages
  97. * in the any of the input fields generated by this helper
  98. *
  99. * @var array
  100. */
  101. public $validationErrors = array();
  102. /**
  103. * Copies the validationErrors variable from the View object into this instance
  104. *
  105. * @param View $View The View this helper is being attached to.
  106. * @param array $settings Configuration settings for the helper.
  107. */
  108. public function __construct(View $View, $settings = array()) {
  109. parent::__construct($View, $settings);
  110. $this->validationErrors =& $View->validationErrors;
  111. }
  112. /**
  113. * Guess the location for a model based on its name and tries to create a new instance
  114. * or get an already created instance of the model
  115. *
  116. * @param string $model
  117. * @return Model model instance
  118. */
  119. protected function _getModel($model) {
  120. $object = null;
  121. if (!$model || $model === 'Model') {
  122. return $object;
  123. }
  124. if (array_key_exists($model, $this->_models)) {
  125. return $this->_models[$model];
  126. }
  127. if (ClassRegistry::isKeySet($model)) {
  128. $object = ClassRegistry::getObject($model);
  129. } elseif (isset($this->request->params['models'][$model])) {
  130. $plugin = $this->request->params['models'][$model]['plugin'];
  131. $plugin .= ($plugin) ? '.' : null;
  132. $object = ClassRegistry::init(array(
  133. 'class' => $plugin . $this->request->params['models'][$model]['className'],
  134. 'alias' => $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 the error
  248. * string. The 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. $error = Set::classicExtract($errors, join('.', $entity));
  265. return $error === null ? false : $error;
  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. $this->defaultModel = $model;
  301. } elseif (empty($model) && empty($this->request->params['models'])) {
  302. $model = false;
  303. }
  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) && $model != $this->defaultModel) {
  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. $last = end($field);
  556. if (is_numeric($last) || empty($last)) {
  557. array_pop($field);
  558. }
  559. $field = implode('.', $field);
  560. if ($lock) {
  561. if (!in_array($field, $this->fields)) {
  562. if ($value !== null) {
  563. return $this->fields[$field] = $value;
  564. }
  565. $this->fields[] = $field;
  566. }
  567. } else {
  568. $this->unlockField($field);
  569. }
  570. }
  571. /**
  572. * Returns true if there is an error for the given field, otherwise false
  573. *
  574. * @param string $field This should be "Modelname.fieldname"
  575. * @return boolean If there are errors this method returns true, else false.
  576. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::isFieldError
  577. */
  578. public function isFieldError($field) {
  579. $this->setEntity($field);
  580. return (bool)$this->tagIsInvalid();
  581. }
  582. /**
  583. * Returns a formatted error message for given FORM field, NULL if no errors.
  584. *
  585. * ### Options:
  586. *
  587. * - `escape` bool Whether or not to html escape the contents of the error.
  588. * - `wrap` mixed Whether or not the error message should be wrapped in a div. If a
  589. * string, will be used as the HTML tag to use.
  590. * - `class` string The classname for the error message
  591. *
  592. * @param string $field A field name, like "Modelname.fieldname"
  593. * @param mixed $text Error message as string or array of messages.
  594. * If array contains `attributes` key it will be used as options for error container
  595. * @param array $options Rendering options for <div /> wrapper tag
  596. * @return string If there are errors this method returns an error message, otherwise null.
  597. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::error
  598. */
  599. public function error($field, $text = null, $options = array()) {
  600. $defaults = array('wrap' => true, 'class' => 'error-message', 'escape' => true);
  601. $options = array_merge($defaults, $options);
  602. $this->setEntity($field);
  603. $error = $this->tagIsInvalid();
  604. if ($error === false) {
  605. return null;
  606. }
  607. if (is_array($text)) {
  608. if (isset($text['attributes']) && is_array($text['attributes'])) {
  609. $options = array_merge($options, $text['attributes']);
  610. unset($text['attributes']);
  611. }
  612. $tmp = array();
  613. foreach ($error as &$e) {
  614. if (isset($text[$e])) {
  615. $tmp []= $text[$e];
  616. } else {
  617. $tmp []= $e;
  618. }
  619. }
  620. $text = $tmp;
  621. }
  622. if ($text !== null) {
  623. $error = $text;
  624. }
  625. if (is_array($error)) {
  626. foreach ($error as &$e) {
  627. if (is_numeric($e)) {
  628. $e = __d('cake', 'Error in field %s', Inflector::humanize($this->field()));
  629. }
  630. }
  631. }
  632. if ($options['escape']) {
  633. $error = h($error);
  634. unset($options['escape']);
  635. }
  636. if (is_array($error)) {
  637. if (count($error) > 1) {
  638. $listParams = array();
  639. if (isset($options['listOptions'])) {
  640. if (is_string($options['listOptions'])) {
  641. $listParams []= $options['listOptions'];
  642. } else {
  643. if (isset($options['listOptions']['itemOptions'])) {
  644. $listParams []= $options['listOptions']['itemOptions'];
  645. unset($options['listOptions']['itemOptions']);
  646. } else {
  647. $listParams []= array();
  648. }
  649. if (isset($options['listOptions']['tag'])) {
  650. $listParams []= $options['listOptions']['tag'];
  651. unset($options['listOptions']['tag']);
  652. }
  653. array_unshift($listParams, $options['listOptions']);
  654. }
  655. unset($options['listOptions']);
  656. }
  657. array_unshift($listParams, $error);
  658. $error = call_user_func_array(array($this->Html, 'nestedList'), $listParams);
  659. } else {
  660. $error = array_pop($error);
  661. }
  662. }
  663. if ($options['wrap']) {
  664. $tag = is_string($options['wrap']) ? $options['wrap'] : 'div';
  665. unset($options['wrap']);
  666. return $this->Html->tag($tag, $error, $options);
  667. } else {
  668. return $error;
  669. }
  670. }
  671. /**
  672. * Returns a formatted LABEL element for HTML FORMs. Will automatically generate
  673. * a for attribute if one is not provided.
  674. *
  675. * ### Options
  676. *
  677. * - `for` - Set the for attribute, if its not defined the for attribute
  678. * will be generated from the $fieldName parameter using
  679. * FormHelper::domId().
  680. *
  681. * Examples:
  682. *
  683. * The text and for attribute are generated off of the fieldname
  684. *
  685. * {{{
  686. * echo $this->Form->label('Post.published');
  687. * <label for="PostPublished">Published</label>
  688. * }}}
  689. *
  690. * Custom text:
  691. *
  692. * {{{
  693. * echo $this->Form->label('Post.published', 'Publish');
  694. * <label for="PostPublished">Publish</label>
  695. * }}}
  696. *
  697. * Custom class name:
  698. *
  699. * {{{
  700. * echo $this->Form->label('Post.published', 'Publish', 'required');
  701. * <label for="PostPublished" class="required">Publish</label>
  702. * }}}
  703. *
  704. * Custom attributes:
  705. *
  706. * {{{
  707. * echo $this->Form->label('Post.published', 'Publish', array(
  708. * 'for' => 'post-publish'
  709. * ));
  710. * <label for="post-publish">Publish</label>
  711. * }}}
  712. *
  713. * @param string $fieldName This should be "Modelname.fieldname"
  714. * @param string $text Text that will appear in the label field. If
  715. * $text is left undefined the text will be inflected from the
  716. * fieldName.
  717. * @param mixed $options An array of HTML attributes, or a string, to be used as a class name.
  718. * @return string The formatted LABEL element
  719. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::label
  720. */
  721. public function label($fieldName = null, $text = null, $options = array()) {
  722. if (empty($fieldName)) {
  723. $fieldName = implode('.', $this->entity());
  724. }
  725. if ($text === null) {
  726. if (strpos($fieldName, '.') !== false) {
  727. $fieldElements = explode('.', $fieldName);
  728. $text = array_pop($fieldElements);
  729. } else {
  730. $text = $fieldName;
  731. }
  732. if (substr($text, -3) == '_id') {
  733. $text = substr($text, 0, strlen($text) - 3);
  734. }
  735. $text = __(Inflector::humanize(Inflector::underscore($text)));
  736. }
  737. if (is_string($options)) {
  738. $options = array('class' => $options);
  739. }
  740. if (isset($options['for'])) {
  741. $labelFor = $options['for'];
  742. unset($options['for']);
  743. } else {
  744. $labelFor = $this->domId($fieldName);
  745. }
  746. return $this->Html->useTag('label', $labelFor, $options, $text);
  747. }
  748. /**
  749. * Generate a set of inputs for `$fields`. If $fields is null the current model
  750. * will be used.
  751. *
  752. * In addition to controller fields output, `$fields` can be used to control legend
  753. * and fieldset rendering with the `fieldset` and `legend` keys.
  754. * `$form->inputs(array('legend' => 'My legend'));` Would generate an input set with
  755. * a custom legend. You can customize individual inputs through `$fields` as well.
  756. *
  757. * {{{
  758. * $form->inputs(array(
  759. * 'name' => array('label' => 'custom label')
  760. * ));
  761. * }}}
  762. *
  763. * In addition to fields control, inputs() allows you to use a few additional options.
  764. *
  765. * - `fieldset` Set to false to disable the fieldset. If a string is supplied it will be used as
  766. * the classname for the fieldset element.
  767. * - `legend` Set to false to disable the legend for the generated input set. Or supply a string
  768. * to customize the legend text.
  769. *
  770. * @param mixed $fields An array of fields to generate inputs for, or null.
  771. * @param array $blacklist a simple array of fields to not create inputs for.
  772. * @return string Completed form inputs.
  773. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::inputs
  774. */
  775. public function inputs($fields = null, $blacklist = null) {
  776. $fieldset = $legend = true;
  777. $model = $this->model();
  778. if (is_array($fields)) {
  779. if (array_key_exists('legend', $fields)) {
  780. $legend = $fields['legend'];
  781. unset($fields['legend']);
  782. }
  783. if (isset($fields['fieldset'])) {
  784. $fieldset = $fields['fieldset'];
  785. unset($fields['fieldset']);
  786. }
  787. } elseif ($fields !== null) {
  788. $fieldset = $legend = $fields;
  789. if (!is_bool($fieldset)) {
  790. $fieldset = true;
  791. }
  792. $fields = array();
  793. }
  794. if (empty($fields)) {
  795. $fields = array_keys($this->_introspectModel($model, 'fields'));
  796. }
  797. if ($legend === true) {
  798. $actionName = __d('cake', 'New %s');
  799. $isEdit = (
  800. strpos($this->request->params['action'], 'update') !== false ||
  801. strpos($this->request->params['action'], 'edit') !== false
  802. );
  803. if ($isEdit) {
  804. $actionName = __d('cake', 'Edit %s');
  805. }
  806. $modelName = Inflector::humanize(Inflector::underscore($model));
  807. $legend = sprintf($actionName, __($modelName));
  808. }
  809. $out = null;
  810. foreach ($fields as $name => $options) {
  811. if (is_numeric($name) && !is_array($options)) {
  812. $name = $options;
  813. $options = array();
  814. }
  815. $entity = explode('.', $name);
  816. $blacklisted = (
  817. is_array($blacklist) &&
  818. (in_array($name, $blacklist) || in_array(end($entity), $blacklist))
  819. );
  820. if ($blacklisted) {
  821. continue;
  822. }
  823. $out .= $this->input($name, $options);
  824. }
  825. if (is_string($fieldset)) {
  826. $fieldsetClass = sprintf(' class="%s"', $fieldset);
  827. } else {
  828. $fieldsetClass = '';
  829. }
  830. if ($fieldset && $legend) {
  831. return $this->Html->useTag('fieldset', $fieldsetClass, $this->Html->useTag('legend', $legend) . $out);
  832. } elseif ($fieldset) {
  833. return $this->Html->useTag('fieldset', $fieldsetClass, $out);
  834. } else {
  835. return $out;
  836. }
  837. }
  838. /**
  839. * Generates a form input element complete with label and wrapper div
  840. *
  841. * ### Options
  842. *
  843. * See each field type method for more information. Any options that are part of
  844. * $attributes or $options for the different **type** methods can be included in `$options` for input().i
  845. * Additionally, any unknown keys that are not in the list below, or part of the selected type's options
  846. * will be treated as a regular html attribute for the generated input.
  847. *
  848. * - `type` - Force the type of widget you want. e.g. `type => 'select'`
  849. * - `label` - Either a string label, or an array of options for the label. See FormHelper::label()
  850. * - `div` - Either `false` to disable the div, or an array of options for the div.
  851. * See HtmlHelper::div() for more options.
  852. * - `options` - for widgets that take options e.g. radio, select
  853. * - `error` - control the error message that is produced
  854. * - `empty` - String or boolean to enable empty select box options.
  855. * - `before` - Content to place before the label + input.
  856. * - `after` - Content to place after the label + input.
  857. * - `between` - Content to place between the label + input.
  858. * - `format` - format template for element order. Any element that is not in the array, will not be in the output.
  859. * - Default input format order: array('before', 'label', 'between', 'input', 'after', 'error')
  860. * - Default checkbox format order: array('before', 'input', 'between', 'label', 'after', 'error')
  861. * - Hidden input will not be formatted
  862. * - Radio buttons cannot have the order of input and label elements controlled with these settings.
  863. *
  864. * @param string $fieldName This should be "Modelname.fieldname"
  865. * @param array $options Each type of input takes different options.
  866. * @return string Completed form widget.
  867. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#creating-form-elements
  868. */
  869. public function input($fieldName, $options = array()) {
  870. $this->setEntity($fieldName);
  871. $options = array_merge(
  872. array('before' => null, 'between' => null, 'after' => null, 'format' => null),
  873. $this->_inputDefaults,
  874. $options
  875. );
  876. $modelKey = $this->model();
  877. $fieldKey = $this->field();
  878. if (!isset($options['type'])) {
  879. $magicType = true;
  880. $options['type'] = 'text';
  881. if (isset($options['options'])) {
  882. $options['type'] = 'select';
  883. } elseif (in_array($fieldKey, array('psword', 'passwd', 'password'))) {
  884. $options['type'] = 'password';
  885. } elseif (isset($options['checked'])) {
  886. $options['type'] = 'checkbox';
  887. } elseif ($fieldDef = $this->_introspectModel($modelKey, 'fields', $fieldKey)) {
  888. $type = $fieldDef['type'];
  889. $primaryKey = $this->fieldset[$modelKey]['key'];
  890. }
  891. if (isset($type)) {
  892. $map = array(
  893. 'string' => 'text', 'datetime' => 'datetime',
  894. 'boolean' => 'checkbox', 'timestamp' => 'datetime',
  895. 'text' => 'textarea', 'time' => 'time',
  896. 'date' => 'date', 'float' => 'number',
  897. 'integer' => 'number'
  898. );
  899. if (isset($this->map[$type])) {
  900. $options['type'] = $this->map[$type];
  901. } elseif (isset($map[$type])) {
  902. $options['type'] = $map[$type];
  903. }
  904. if ($fieldKey == $primaryKey) {
  905. $options['type'] = 'hidden';
  906. }
  907. if (
  908. $options['type'] === 'number' &&
  909. $type === 'float' &&
  910. !isset($options['step'])
  911. ) {
  912. $options['step'] = 'any';
  913. }
  914. }
  915. if (preg_match('/_id$/', $fieldKey) && $options['type'] !== 'hidden') {
  916. $options['type'] = 'select';
  917. }
  918. if ($modelKey === $fieldKey) {
  919. $options['type'] = 'select';
  920. if (!isset($options['multiple'])) {
  921. $options['multiple'] = 'multiple';
  922. }
  923. }
  924. }
  925. $types = array('checkbox', 'radio', 'select');
  926. if (
  927. (!isset($options['options']) && in_array($options['type'], $types)) ||
  928. (isset($magicType) && $options['type'] == 'text')
  929. ) {
  930. $varName = Inflector::variable(
  931. Inflector::pluralize(preg_replace('/_id$/', '', $fieldKey))
  932. );
  933. $varOptions = $this->_View->getVar($varName);
  934. if (is_array($varOptions)) {
  935. if ($options['type'] !== 'radio') {
  936. $options['type'] = 'select';
  937. }
  938. $options['options'] = $varOptions;
  939. }
  940. }
  941. $autoLength = (!array_key_exists('maxlength', $options) && isset($fieldDef['length']));
  942. if ($autoLength && $options['type'] == 'text') {
  943. $options['maxlength'] = $fieldDef['length'];
  944. }
  945. if ($autoLength && $fieldDef['type'] == 'float') {
  946. $options['maxlength'] = array_sum(explode(',', $fieldDef['length']))+1;
  947. }
  948. $divOptions = array();
  949. $div = $this->_extractOption('div', $options, true);
  950. unset($options['div']);
  951. if (!empty($div)) {
  952. $divOptions['class'] = 'input';
  953. $divOptions = $this->addClass($divOptions, $options['type']);
  954. if (is_string($div)) {
  955. $divOptions['class'] = $div;
  956. } elseif (is_array($div)) {
  957. $divOptions = array_merge($divOptions, $div);
  958. }
  959. if ($this->_introspectModel($modelKey, 'validates', $fieldKey)) {
  960. $divOptions = $this->addClass($divOptions, 'required');
  961. }
  962. if (!isset($divOptions['tag'])) {
  963. $divOptions['tag'] = 'div';
  964. }
  965. }
  966. $label = null;
  967. if (isset($options['label']) && $options['type'] !== 'radio') {
  968. $label = $options['label'];
  969. unset($options['label']);
  970. }
  971. if ($options['type'] === 'radio') {
  972. $label = false;
  973. if (isset($options['options'])) {
  974. $radioOptions = (array)$options['options'];
  975. unset($options['options']);
  976. }
  977. }
  978. if ($label !== false) {
  979. $label = $this->_inputLabel($fieldName, $label, $options);
  980. }
  981. $error = $this->_extractOption('error', $options, null);
  982. unset($options['error']);
  983. $selected = $this->_extractOption('selected', $options, null);
  984. unset($options['selected']);
  985. if (isset($options['rows']) || isset($options['cols'])) {
  986. $options['type'] = 'textarea';
  987. }
  988. if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time' || $options['type'] === 'select') {
  989. $options += array('empty' => false);
  990. }
  991. if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time') {
  992. $dateFormat = $this->_extractOption('dateFormat', $options, 'MDY');
  993. $timeFormat = $this->_extractOption('timeFormat', $options, 12);
  994. unset($options['dateFormat'], $options['timeFormat']);
  995. }
  996. $type = $options['type'];
  997. $out = array_merge(
  998. array('before' => null, 'label' => null, 'between' => null, 'input' => null, 'after' => null, 'error' => null),
  999. array('before' => $options['before'], 'label' => $label, 'between' => $options['between'], 'after' => $options['after'])
  1000. );
  1001. $format = null;
  1002. if (is_array($options['format']) && in_array('input', $options['format'])) {
  1003. $format = $options['format'];
  1004. }
  1005. unset($options['type'], $options['before'], $options['between'], $options['after'], $options['format']);
  1006. switch ($type) {
  1007. case 'hidden':
  1008. $input = $this->hidden($fieldName, $options);
  1009. $format = array('input');
  1010. unset($divOptions);
  1011. break;
  1012. case 'checkbox':
  1013. $input = $this->checkbox($fieldName, $options);
  1014. $format = $format ? $format : array('before', 'input', 'between', 'label', 'after', 'error');
  1015. break;
  1016. case 'radio':
  1017. $input = $this->radio($fieldName, $radioOptions, $options);
  1018. break;
  1019. case 'file':
  1020. $input = $this->file($fieldName, $options);
  1021. break;
  1022. case 'select':
  1023. $options += array('options' => array(), 'value' => $selected);
  1024. $list = $options['options'];
  1025. unset($options['options']);
  1026. $input = $this->select($fieldName, $list, $options);
  1027. break;
  1028. case 'time':
  1029. $options['value'] = $selected;
  1030. $input = $this->dateTime($fieldName, null, $timeFormat, $options);
  1031. break;
  1032. case 'date':
  1033. $options['value'] = $selected;
  1034. $input = $this->dateTime($fieldName, $dateFormat, null, $options);
  1035. break;
  1036. case 'datetime':
  1037. $options['value'] = $selected;
  1038. $input = $this->dateTime($fieldName, $dateFormat, $timeFormat, $options);
  1039. break;
  1040. case 'textarea':
  1041. $input = $this->textarea($fieldName, $options + array('cols' => '30', 'rows' => '6'));
  1042. break;
  1043. case 'url':
  1044. $input = $this->text($fieldName, array('type' => 'url') + $options);
  1045. break;
  1046. default:
  1047. $input = $this->{$type}($fieldName, $options);
  1048. }
  1049. if ($type != 'hidden' && $error !== false) {
  1050. $errMsg = $this->error($fieldName, $error);
  1051. if ($errMsg) {
  1052. $divOptions = $this->addClass($divOptions, 'error');
  1053. $out['error'] = $errMsg;
  1054. }
  1055. }
  1056. $out['input'] = $input;
  1057. $format = $format ? $format : array('before', 'label', 'between', 'input', 'after', 'error');
  1058. $output = '';
  1059. foreach ($format as $element) {
  1060. $output .= $out[$element];
  1061. unset($out[$element]);
  1062. }
  1063. if (!empty($divOptions['tag'])) {
  1064. $tag = $divOptions['tag'];
  1065. unset($divOptions['tag']);
  1066. $output = $this->Html->tag($tag, $output, $divOptions);
  1067. }
  1068. return $output;
  1069. }
  1070. /**
  1071. * Extracts a single option from an options array.
  1072. *
  1073. * @param string $name The name of the option to pull out.
  1074. * @param array $options The array of options you want to extract.
  1075. * @param mixed $default The default option value
  1076. * @return mixed the contents of the option or default
  1077. */
  1078. protected function _extractOption($name, $options, $default = null) {
  1079. if (array_key_exists($name, $options)) {
  1080. return $options[$name];
  1081. }
  1082. return $default;
  1083. }
  1084. /**
  1085. * Generate a label for an input() call.
  1086. *
  1087. * @param string $fieldName
  1088. * @param string $label
  1089. * @param array $options Options for the label element.
  1090. * @return string Generated label element
  1091. */
  1092. protected function _inputLabel($fieldName, $label, $options) {
  1093. $labelAttributes = $this->domId(array(), 'for');
  1094. if ($options['type'] === 'date' || $options['type'] === 'datetime') {
  1095. if (isset($options['dateFormat']) && $options['dateFormat'] === 'NONE') {
  1096. $labelAttributes['for'] .= 'Hour';
  1097. $idKey = 'hour';
  1098. } else {
  1099. $labelAttributes['for'] .= 'Month';
  1100. $idKey = 'month';
  1101. }
  1102. if (isset($options['id']) && isset($options['id'][$idKey])) {
  1103. $labelAttributes['for'] = $options['id'][$idKey];
  1104. }
  1105. } elseif ($options['type'] === 'time') {
  1106. $labelAttributes['for'] .= 'Hour';
  1107. if (isset($options['id']) && isset($options['id']['hour'])) {
  1108. $labelAttributes['for'] = $options['id']['hour'];
  1109. }
  1110. }
  1111. if (is_array($label)) {
  1112. $labelText = null;
  1113. if (isset($label['text'])) {
  1114. $labelText = $label['text'];
  1115. unset($label['text']);
  1116. }
  1117. $labelAttributes = array_merge($labelAttributes, $label);
  1118. } else {
  1119. $labelText = $label;
  1120. }
  1121. if (isset($options['id']) && is_string($options['id'])) {
  1122. $labelAttributes = array_merge($labelAttributes, array('for' => $options['id']));
  1123. }
  1124. return $this->label($fieldName, $labelText, $labelAttributes);
  1125. }
  1126. /**
  1127. * Creates a checkbox input widget.
  1128. *
  1129. * ### Options:
  1130. *
  1131. * - `value` - the value of the checkbox
  1132. * - `checked` - boolean indicate that this checkbox is checked.
  1133. * - `hiddenField` - boolean to indicate if you want the results of checkbox() to include
  1134. * a hidden input with a value of ''.
  1135. * - `disabled` - create a disabled input.
  1136. * - `default` - Set the default value for the checkbox. This allows you to start checkboxes
  1137. * as checked, without having to check the POST data. A matching POST data value, will overwrite
  1138. * the default value.
  1139. *
  1140. * @param string $fieldName Name of a field, like this "Modelname.fieldname"
  1141. * @param array $options Array of HTML attributes.
  1142. * @return string An HTML text input element.
  1143. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
  1144. */
  1145. public function checkbox($fieldName, $options = array()) {
  1146. $valueOptions = array();
  1147. if (isset($options['default'])) {
  1148. $valueOptions['default'] = $options['default'];
  1149. unset($options['default']);
  1150. }
  1151. $options = $this->_initInputField($fieldName, $options) + array('hiddenField' => true);
  1152. $value = current($this->value($valueOptions));
  1153. $output = "";
  1154. if (empty($options['value'])) {
  1155. $options['value'] = 1;
  1156. }
  1157. if (
  1158. (!isset($options['checked']) && !empty($value) && $value == $options['value']) ||
  1159. !empty($options['checked'])
  1160. ) {
  1161. $options['checked'] = 'checked';
  1162. }
  1163. if ($options['hiddenField']) {
  1164. $hiddenOptions = array(
  1165. 'id' => $options['id'] . '_', 'name' => $options['name'],
  1166. 'value' => '0', 'secure' => false
  1167. );
  1168. if (isset($options['disabled']) && $options['disabled'] == true) {
  1169. $hiddenOptions['disabled'] = 'disabled';
  1170. }
  1171. $output = $this->hidden($fieldName, $hiddenOptions);
  1172. }
  1173. unset($options['hiddenField']);
  1174. return $output . $this->Html->useTag('checkbox', $options['name'], array_diff_key($options, array('name' => '')));
  1175. }
  1176. /**
  1177. * Creates a set of radio widgets. Will create a legend and fieldset
  1178. * by default. Use $options to control this
  1179. *
  1180. * ### Attributes:
  1181. *
  1182. * - `separator` - define the string in between the radio buttons
  1183. * - `legend` - control whether or not the widget set has a fieldset & legend
  1184. * - `value` - indicate a value that is should be checked
  1185. * - `label` - boolean to indicate whether or not labels for widgets show be displayed
  1186. * - `hiddenField` - boolean to indicate if you want the results of radio() to include
  1187. * a hidden input with a value of ''. This is useful for creating radio sets that non-continuous
  1188. *
  1189. * @param string $fieldName Name of a field, like this "Modelname.fieldname"
  1190. * @param array $options Radio button options array.
  1191. * @param array $attributes Array of HTML attributes, and special attributes above.
  1192. * @return string Completed radio widget set.
  1193. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
  1194. */
  1195. public function radio($fieldName, $options = array(), $attributes = array()) {
  1196. $attributes = $this->_initInputField($fieldName, $attributes);
  1197. $legend = false;
  1198. $disabled = array();
  1199. if (isset($attributes['legend'])) {
  1200. $legend = $attributes['legend'];
  1201. unset($attributes['legend']);
  1202. } elseif (count($options) > 1) {
  1203. $legend = __(Inflector::humanize($this->field()));
  1204. }
  1205. $label = true;
  1206. if (isset($attributes['label'])) {
  1207. $label = $attributes['label'];
  1208. unset($attributes['label']);
  1209. }
  1210. $inbetween = null;
  1211. if (isset($attributes['separator'])) {
  1212. $inbetween = $attributes['separator'];
  1213. unset($attributes['separator']);
  1214. }
  1215. if (isset($attributes['value'])) {
  1216. $value = $attributes['value'];
  1217. } else {
  1218. $value = $this->value($fieldName);
  1219. }
  1220. if (isset($attributes['disabled'])) {
  1221. $disabled = $attributes['disabled'];
  1222. }
  1223. $out = array();
  1224. $hiddenField = isset($attributes['hiddenField']) ? $attributes['hiddenField'] : true;
  1225. unset($attributes['hiddenField']);
  1226. foreach ($options as $optValue => $optTitle) {
  1227. $optionsHere = array('value' => $optValue);
  1228. if (isset($value) && $optValue == $value) {
  1229. $optionsHere['checked'] = 'checked';
  1230. }
  1231. if (!empty($disabled) && in_array($optValue, $disabled)) {
  1232. $optionsHere['disabled'] = true;
  1233. }
  1234. $tagName = Inflector::camelize(
  1235. $attributes['id'] . '_' . Inflector::slug($optValue)
  1236. );
  1237. if ($label) {
  1238. $optTitle = $this->Html->useTag('label', $tagName, '', $optTitle);
  1239. }
  1240. $allOptions = array_merge($attributes, $optionsHere);
  1241. $out[] = $this->Html->useTag('radio', $attributes['name'], $tagName,
  1242. array_diff_key($allOptions, array('name' => '', 'type' => '', 'id' => '')),
  1243. $optTitle
  1244. );
  1245. }
  1246. $hidden = null;
  1247. if ($hiddenField) {
  1248. if (!isset($value) || $value === '') {
  1249. $hidden = $this->hidden($fieldName, array(
  1250. 'id' => $attributes['id'] . '_', 'value' => '', 'name' => $attributes['name']
  1251. ));
  1252. }
  1253. }
  1254. $out = $hidden . implode($inbetween, $out);
  1255. if ($legend) {
  1256. $out = $this->Html->useTag('fieldset', '', $this->Html->useTag('legend', $legend) . $out);
  1257. }
  1258. return $out;
  1259. }
  1260. /**
  1261. * Missing method handler - implements various simple input types. Is used to create inputs
  1262. * of various types. e.g. `$this->Form->text();` will create `<input type="text" />` while
  1263. * `$this->Form->range();` will create `<input type="range" />`
  1264. *
  1265. * ### Usage
  1266. *
  1267. * `$this->Form->search('User.query', array('value' => 'test'));`
  1268. *
  1269. * Will make an input like:
  1270. *
  1271. * `<input type="search" id="UserQuery" name="data[User][query]" value="test" />`
  1272. *
  1273. * The first argument to an input type should always be the fieldname, in `Model.field` format.
  1274. * The second argument should always be an array of attributes for the input.
  1275. *
  1276. * @param string $method Method name / input type to make.
  1277. * @param array $params Parameters for the method call
  1278. * @return string Formatted input method.
  1279. * @throws CakeException When there are no params for the method call.
  1280. */
  1281. public function __call($method, $params) {
  1282. $options = array();
  1283. if (empty($params)) {
  1284. throw new CakeException(__d('cake_dev', 'Missing field name for FormHelper::%s', $method));
  1285. }
  1286. if (isset($params[1])) {
  1287. $options = $params[1];
  1288. }
  1289. if (!isset($options['type'])) {
  1290. $options['type'] = $method;
  1291. }
  1292. $options = $this->_initInputField($params[0], $options);
  1293. return $this->Html->useTag('input', $options['name'], array_diff_key($options, array('name' => '')));
  1294. }
  1295. /**
  1296. * Creates a textarea widget.
  1297. *
  1298. * ### Options:
  1299. *
  1300. * - `escape` - Whether or not the contents of the textarea should be escaped. Defaults to true.
  1301. *
  1302. * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
  1303. * @param array $options Array of HTML attributes, and special options above.
  1304. * @return string A generated HTML text input element
  1305. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::textarea
  1306. */
  1307. public function textarea($fieldName, $options = array()) {
  1308. $options = $this->_initInputField($fieldName, $options);
  1309. $value = null;
  1310. if (array_key_exists('value', $options)) {
  1311. $value = $options['value'];
  1312. if (!array_key_exists('escape', $options) || $options['escape'] !== false) {
  1313. $value = h($value);
  1314. }
  1315. unset($options['value']);
  1316. }
  1317. return $this->Html->useTag('textarea', $options['name'], array_diff_key($options, array('type' => '', 'name' => '')), $value);
  1318. }
  1319. /**
  1320. * Creates a hidden input field.
  1321. *
  1322. * @param string $fieldName Name of a field, in the form of "Modelname.fieldname"
  1323. * @param array $options Array of HTML attributes.
  1324. * @return string A generated hidden input
  1325. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hidden
  1326. */
  1327. public function hidden($fieldName, $options = array()) {
  1328. $secure = true;
  1329. if (isset($options['secure'])) {
  1330. $secure = $options['secure'];
  1331. unset($options['secure']);
  1332. }
  1333. $options = $this->_initInputField($fieldName, array_merge(
  1334. $options, array('secure' => self::SECURE_SKIP)
  1335. ));
  1336. if ($secure && $secure !== self::SECURE_SKIP) {
  1337. $this->_secure(true, null, '' . $options['value']);
  1338. }
  1339. return $this->Html->useTag('hidden', $options['name'], array_diff_key($options, array('name' => '')));
  1340. }
  1341. /**
  1342. * Creates file input widget.
  1343. *
  1344. * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
  1345. * @param array $options Array of HTML attributes.
  1346. * @return string A generated file input.
  1347. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::file
  1348. */
  1349. public function file($fieldName, $options = array()) {
  1350. $options += array('secure' => true);
  1351. $secure = $options['secure'];
  1352. $options['secure'] = self::SECURE_SKIP;
  1353. $options = $this->_initInputField($fieldName, $options);
  1354. $field = $this->entity();
  1355. foreach (array('name', 'type', 'tmp_name', 'error', 'size') as $suffix) {
  1356. $this->_secure($secure, array_merge($field, array($suffix)));
  1357. }
  1358. return $this->Html->useTag('file', $options['name'], array_diff_key($options, array('name' => '')));
  1359. }
  1360. /**
  1361. * Creates a `<button>` tag. The type attribute defaults to `type="submit"`
  1362. * You can change it to a different value by using `$options['type']`.
  1363. *
  1364. * ### Options:
  1365. *
  1366. * - `escape` - HTML entity encode the $title of the button. Defaults to false.
  1367. *
  1368. * @param string $title The button's caption. Not automatically HTML encoded
  1369. * @param array $options Array of options and HTML attributes.
  1370. * @return string A HTML button tag.
  1371. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::button
  1372. */
  1373. public function button($title, $options = array()) {
  1374. $options += array('type' => 'submit', 'escape' => false, 'secure' => false);
  1375. if ($options['escape']) {
  1376. $title = h($title);
  1377. }
  1378. if (isset($options['name'])) {
  1379. $name = str_replace(array('[', ']'), array('.', ''), $options['name']);
  1380. $this->_secure($options['secure'], $name);
  1381. }
  1382. return $this->Html->useTag('button', $options['type'], array_diff_key($options, array('type' => '')), $title);
  1383. }
  1384. /**
  1385. * Create a `<button>` tag with a surrounding `<form>` that submits via POST.
  1386. *
  1387. * This method creates a `<form>` element. So do not use this method in some opened form.
  1388. * Instead use FormHelper::submit() or FormHelper::button() to create buttons inside opened forms.
  1389. *
  1390. * ### Options:
  1391. *
  1392. * - `data` - Array with key/value to pass in input hidden
  1393. * - Other options is the same of button method.
  1394. *
  1395. * @param string $title The button's caption. Not automatically HTML encoded
  1396. * @param mixed $url URL as string or array
  1397. * @param array $options Array of options and HTML attributes.
  1398. * @return string A HTML button tag.
  1399. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postButton
  1400. */
  1401. public function postButton($title, $url, $options = array()) {
  1402. $out = $this->create(false, array('id' => false, 'url' => $url, 'style' => 'display:none;'));
  1403. if (isset($options['data']) && is_array($options['data'])) {

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