PageRenderTime 65ms CodeModel.GetById 25ms 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
  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'])) {
  1404. foreach ($options['data'] as $key => $value) {
  1405. $out .= $this->hidden($key, array('value' => $value, 'id' => false));
  1406. }
  1407. unset($options['data']);
  1408. }
  1409. $out .= $this->button($title, $options);
  1410. $out .= $this->end();
  1411. return $out;
  1412. }
  1413. /**
  1414. * Creates an HTML link, but access the url using method POST.
  1415. * Requires javascript to be enabled in browser.
  1416. *
  1417. * This method creates a `<form>` element. So do not use this method inside an existing form.
  1418. * Instead you should add a submit button using FormHelper::submit()
  1419. *
  1420. * ### Options:
  1421. *
  1422. * - `data` - Array with key/value to pass in input hidden
  1423. * - `confirm` - Can be used instead of $confirmMessage.
  1424. * - Other options is the same of HtmlHelper::link() method.
  1425. * - The option `onclick` will be replaced.
  1426. *
  1427. * @param string $title The content to be wrapped by <a> tags.
  1428. * @param mixed $url Cake-relative URL or array of URL parameters, or external URL (starts with http://)
  1429. * @param array $options Array of HTML attributes.
  1430. * @param string $confirmMessage JavaScript confirmation message.
  1431. * @return string An `<a />` element.
  1432. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postLink
  1433. */
  1434. public function postLink($title, $url = null, $options = array(), $confirmMessage = false) {
  1435. if (!empty($options['confirm'])) {
  1436. $confirmMessage = $options['confirm'];
  1437. unset($options['confirm']);
  1438. }
  1439. $formName = uniqid('post_');
  1440. $formUrl = $this->url($url);
  1441. $out = $this->Html->useTag('form', $formUrl, array('name' => $formName, 'id' => $formName, 'style' => 'display:none;', 'method' => 'post'));
  1442. $out .= $this->Html->useTag('hidden', '_method', ' value="POST"');
  1443. $out .= $this->_csrfField();
  1444. $fields = array();
  1445. if (isset($options['data']) && is_array($options['data'])) {
  1446. foreach ($options['data'] as $key => $value) {
  1447. $fields[$key] = $value;
  1448. $out .= $this->hidden($key, array('value' => $value, 'id' => false));
  1449. }
  1450. unset($options['data']);
  1451. }
  1452. $out .= $this->secure($fields);
  1453. $out .= $this->Html->useTag('formend');
  1454. $url = '#';
  1455. $onClick = 'document.' . $formName . '.submit();';
  1456. if ($confirmMessage) {
  1457. $confirmMessage = str_replace(array("'", '"'), array("\'", '\"'), $confirmMessage);
  1458. $options['onclick'] = "if (confirm('{$confirmMessage}')) { {$onClick} }";
  1459. } else {
  1460. $options['onclick'] = $onClick;
  1461. }
  1462. $options['onclick'] .= ' event.returnValue = false; return false;';
  1463. $out .= $this->Html->link($title, $url, $options);
  1464. return $out;
  1465. }
  1466. /**
  1467. * Creates a submit button element. This method will generate `<input />` elements that
  1468. * can be used to submit, and reset forms by using $options. image submits can be created by supplying an
  1469. * image path for $caption.
  1470. *
  1471. * ### Options
  1472. *
  1473. * - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to
  1474. * FormHelper::input().
  1475. * - `before` - Content to include before the input.
  1476. * - `after` - Content to include after the input.
  1477. * - `type` - Set to 'reset' for reset inputs. Defaults to 'submit'
  1478. * - Other attributes will be assigned to the input element.
  1479. *
  1480. * ### Options
  1481. *
  1482. * - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to
  1483. * FormHelper::input().
  1484. * - Other attributes will be assigned to the input element.
  1485. *
  1486. * @param string $caption The label appearing on the button OR if string contains :// or the
  1487. * extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension
  1488. * exists, AND the first character is /, image is relative to webroot,
  1489. * OR if the first character is not /, image is relative to webroot/img.
  1490. * @param array $options Array of options. See above.
  1491. * @return string A HTML submit button
  1492. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::submit
  1493. */
  1494. public function submit($caption = null, $options = array()) {
  1495. if (!is_string($caption) && empty($caption)) {
  1496. $caption = __d('cake', 'Submit');
  1497. }
  1498. $out = null;
  1499. $div = true;
  1500. if (isset($options['div'])) {
  1501. $div = $options['div'];
  1502. unset($options['div']);
  1503. }
  1504. $options += array('type' => 'submit', 'before' => null, 'after' => null, 'secure' => false);
  1505. $divOptions = array('tag' => 'div');
  1506. if ($div === true) {
  1507. $divOptions['class'] = 'submit';
  1508. } elseif ($div === false) {
  1509. unset($divOptions);
  1510. } elseif (is_string($div)) {
  1511. $divOptions['class'] = $div;
  1512. } elseif (is_array($div)) {
  1513. $divOptions = array_merge(array('class' => 'submit', 'tag' => 'div'), $div);
  1514. }
  1515. if (isset($options['name'])) {
  1516. $name = str_replace(array('[', ']'), array('.', ''), $options['name']);
  1517. $this->_secure($options['secure'], $name);
  1518. }
  1519. unset($options['secure']);
  1520. $before = $options['before'];
  1521. $after = $options['after'];
  1522. unset($options['before'], $options['after']);
  1523. $isUrl = strpos($caption, '://') !== false;
  1524. $isImage = preg_match('/\.(jpg|jpe|jpeg|gif|png|ico)$/', $caption);
  1525. if ($isUrl || $isImage) {
  1526. $unlockFields = array('x', 'y');
  1527. if (isset($options['name'])) {
  1528. $unlockFields = array(
  1529. $options['name'] . '_x', $options['name'] . '_y'
  1530. );
  1531. }
  1532. foreach ($unlockFields as $ignore) {
  1533. $this->unlockField($ignore);
  1534. }
  1535. }
  1536. if ($isUrl) {
  1537. unset($options['type']);
  1538. $tag = $this->Html->useTag('submitimage', $caption, $options);
  1539. } elseif ($isImage) {
  1540. unset($options['type']);
  1541. if ($caption{0} !== '/') {
  1542. $url = $this->webroot(IMAGES_URL . $caption);
  1543. } else {
  1544. $url = $this->webroot(trim($caption, '/'));
  1545. }
  1546. $url = $this->assetTimestamp($url);
  1547. $tag = $this->Html->useTag('submitimage', $url, $options);
  1548. } else {
  1549. $options['value'] = $caption;
  1550. $tag = $this->Html->useTag('submit', $options);
  1551. }
  1552. $out = $before . $tag . $after;
  1553. if (isset($divOptions)) {
  1554. $tag = $divOptions['tag'];
  1555. unset($divOptions['tag']);
  1556. $out = $this->Html->tag($tag, $out, $divOptions);
  1557. }
  1558. return $out;
  1559. }
  1560. /**
  1561. * Returns a formatted SELECT element.
  1562. *
  1563. * ### Attributes:
  1564. *
  1565. * - `showParents` - If included in the array and set to true, an additional option element
  1566. * will be added for the parent of each option group. You can set an option with the same name
  1567. * and it's key will be used for the value of the option.
  1568. * - `multiple` - show a multiple select box. If set to 'checkbox' multiple checkboxes will be
  1569. * created instead.
  1570. * - `empty` - If true, the empty select option is shown. If a string,
  1571. * that string is displayed as the empty element.
  1572. * - `escape` - If true contents of options will be HTML entity encoded. Defaults to true.
  1573. * - `value` The selected value of the input.
  1574. * - `class` - When using multiple = checkbox the classname to apply to the divs. Defaults to 'checkbox'.
  1575. *
  1576. * ### Using options
  1577. *
  1578. * A simple array will create normal options:
  1579. *
  1580. * {{{
  1581. * $options = array(1 => 'one', 2 => 'two);
  1582. * $this->Form->select('Model.field', $options));
  1583. * }}}
  1584. *
  1585. * While a nested options array will create optgroups with options inside them.
  1586. * {{{
  1587. * $options = array(
  1588. * 1 => 'bill',
  1589. * 'fred' => array(
  1590. * 2 => 'fred',
  1591. * 3 => 'fred jr.'
  1592. * )
  1593. * );
  1594. * $this->Form->select('Model.field', $options);
  1595. * }}}
  1596. *
  1597. * In the above `2 => 'fred'` will not generate an option element. You should enable the `showParents`
  1598. * attribute to show the fred option.
  1599. *
  1600. * If you have multiple options that need to have the same value attribute, you can
  1601. * use an array of arrays to express this:
  1602. *
  1603. * {{{
  1604. * $options = array(
  1605. * array('name' => 'United states', 'value' => 'USA'),
  1606. * array('name' => 'USA', 'value' => 'USA'),
  1607. * );
  1608. * }}}
  1609. *
  1610. * @param string $fieldName Name attribute of the SELECT
  1611. * @param array $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the
  1612. * SELECT element
  1613. * @param array $attributes The HTML attributes of the select element.
  1614. * @return string Formatted SELECT element
  1615. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
  1616. */
  1617. public function select($fieldName, $options = array(), $attributes = array()) {
  1618. $select = array();
  1619. $style = null;
  1620. $tag = null;
  1621. $attributes += array(
  1622. 'class' => null,
  1623. 'escape' => true,
  1624. 'secure' => true,
  1625. 'empty' => '',
  1626. 'showParents' => false,
  1627. 'hiddenField' => true
  1628. );
  1629. $escapeOptions = $this->_extractOption('escape', $attributes);
  1630. $secure = $this->_extractOption('secure', $attributes);
  1631. $showEmpty = $this->_extractOption('empty', $attributes);
  1632. $showParents = $this->_extractOption('showParents', $attributes);
  1633. $hiddenField = $this->_extractOption('hiddenField', $attributes);
  1634. unset($attributes['escape'], $attributes['secure'], $attributes['empty'], $attributes['showParents'], $attributes['hiddenField']);
  1635. $id = $this->_extractOption('id', $attributes);
  1636. $attributes = $this->_initInputField($fieldName, array_merge(
  1637. (array)$attributes, array('secure' => self::SECURE_SKIP)
  1638. ));
  1639. if (is_string($options) && isset($this->_options[$options])) {
  1640. $options = $this->_generateOptions($options);
  1641. } elseif (!is_array($options)) {
  1642. $options = array();
  1643. }
  1644. if (isset($attributes['type'])) {
  1645. unset($attributes['type']);
  1646. }
  1647. if (!empty($attributes['multiple'])) {
  1648. $style = ($attributes['multiple'] === 'checkbox') ? 'checkbox' : null;
  1649. $template = ($style) ? 'checkboxmultiplestart' : 'selectmultiplestart';
  1650. $tag = $template;
  1651. if ($hiddenField) {
  1652. $hiddenAttributes = array(
  1653. 'value' => '',
  1654. 'id' => $attributes['id'] . ($style ? '' : '_'),
  1655. 'secure' => false,
  1656. 'name' => $attributes['name']
  1657. );
  1658. $select[] = $this->hidden(null, $hiddenAttributes);
  1659. }
  1660. } else {
  1661. $tag = 'selectstart';
  1662. }
  1663. if (!empty($tag) || isset($template)) {
  1664. if (!isset($secure) || $secure == true) {
  1665. $this->_secure(true);
  1666. }
  1667. $select[] = $this->Html->useTag($tag, $attributes['name'], array_diff_key($attributes, array('name' => '', 'value' => '')));
  1668. }
  1669. $emptyMulti = (
  1670. $showEmpty !== null && $showEmpty !== false && !(
  1671. empty($showEmpty) && (isset($attributes) &&
  1672. array_key_exists('multiple', $attributes))
  1673. )
  1674. );
  1675. if ($emptyMulti) {
  1676. $showEmpty = ($showEmpty === true) ? '' : $showEmpty;
  1677. $options = array_reverse($options, true);
  1678. $options[''] = $showEmpty;
  1679. $options = array_reverse($options, true);
  1680. }
  1681. if (!$id) {
  1682. $attributes['id'] = Inflector::camelize($attributes['id']);
  1683. }
  1684. $select = array_merge($select, $this->_selectOptions(
  1685. array_reverse($options, true),
  1686. array(),
  1687. $showParents,
  1688. array(
  1689. 'escape' => $escapeOptions,
  1690. 'style' => $style,
  1691. 'name' => $attributes['name'],
  1692. 'value' => $attributes['value'],
  1693. 'class' => $attributes['class'],
  1694. 'id' => $attributes['id']
  1695. )
  1696. ));
  1697. $template = ($style == 'checkbox') ? 'checkboxmultipleend' : 'selectend';
  1698. $select[] = $this->Html->useTag($template);
  1699. return implode("\n", $select);
  1700. }
  1701. /**
  1702. * Returns a SELECT element for days.
  1703. *
  1704. * ### Attributes:
  1705. *
  1706. * - `empty` - If true, the empty select option is shown. If a string,
  1707. * that string is displayed as the empty element.
  1708. * - `value` The selected value of the input.
  1709. *
  1710. * @param string $fieldName Prefix name for the SELECT element
  1711. * @param array $attributes HTML attributes for the select element
  1712. * @return string A generated day select box.
  1713. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::day
  1714. */
  1715. public function day($fieldName = null, $attributes = array()) {
  1716. $attributes += array('empty' => true, 'value' => null);
  1717. $attributes = $this->_dateTimeSelected('day', $fieldName, $attributes);
  1718. if (strlen($attributes['value']) > 2) {
  1719. $attributes['value'] = date('d', strtotime($attributes['value']));
  1720. } elseif ($attributes['value'] === false) {
  1721. $attributes['value'] = null;
  1722. }
  1723. return $this->select($fieldName . ".day", $this->_generateOptions('day'), $attributes);
  1724. }
  1725. /**
  1726. * Returns a SELECT element for years
  1727. *
  1728. * ### Attributes:
  1729. *
  1730. * - `empty` - If true, the empty select option is shown. If a string,
  1731. * that string is displayed as the empty element.
  1732. * - `orderYear` - Ordering of year values in select options.
  1733. * Possible values 'asc', 'desc'. Default 'desc'
  1734. * - `value` The selected value of the input.
  1735. *
  1736. * @param string $fieldName Prefix name for the SELECT element
  1737. * @param integer $minYear First year in sequence
  1738. * @param integer $maxYear Last year in sequence
  1739. * @param array $attributes Attribute array for the select elements.
  1740. * @return string Completed year select input
  1741. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::year
  1742. */
  1743. public function year($fieldName, $minYear = null, $maxYear = null, $attributes = array()) {
  1744. $attributes += array('empty' => true, 'value' => null);
  1745. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  1746. if (is_array($value)) {
  1747. extract($value);
  1748. $attributes['value'] = $year;
  1749. } else {
  1750. if (empty($value)) {
  1751. if (!$attributes['empty'] && !$maxYear) {
  1752. $attributes['value'] = 'now';
  1753. } elseif (!$attributes['empty'] && $maxYear && !$attributes['value']) {
  1754. $attributes['value'] = $maxYear;
  1755. }
  1756. } else {
  1757. $attributes['value'] = $value;
  1758. }
  1759. }
  1760. }
  1761. if (strlen($attributes['value']) > 4 || $attributes['value'] === 'now') {
  1762. $attributes['value'] = date('Y', strtotime($attributes['value']));
  1763. } elseif ($attributes['value'] === false) {
  1764. $attributes['value'] = null;
  1765. }
  1766. $yearOptions = array('min' => $minYear, 'max' => $maxYear, 'order' => 'desc');
  1767. if (isset($attributes['orderYear'])) {
  1768. $yearOptions['order'] = $attributes['orderYear'];
  1769. unset($attributes['orderYear']);
  1770. }
  1771. return $this->select(
  1772. $fieldName . '.year', $this->_generateOptions('year', $yearOptions),
  1773. $attributes
  1774. );
  1775. }
  1776. /**
  1777. * Returns a SELECT element for months.
  1778. *
  1779. * ### Attributes:
  1780. *
  1781. * - `monthNames` - If false, 2 digit numbers will be used instead of text.
  1782. * If a array, the given array will be used.
  1783. * - `empty` - If true, the empty select option is shown. If a string,
  1784. * that string is displayed as the empty element.
  1785. * - `value` The selected value of the input.
  1786. *
  1787. * @param string $fieldName Prefix name for the SELECT element
  1788. * @param array $attributes Attributes for the select element
  1789. * @return string A generated month select dropdown.
  1790. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::month
  1791. */
  1792. public function month($fieldName, $attributes = array()) {
  1793. $attributes += array('empty' => true, 'value' => null);
  1794. $attributes = $this->_dateTimeSelected('month', $fieldName, $attributes);
  1795. if (strlen($attributes['value']) > 2) {
  1796. $attributes['value'] = date('m', strtotime($attributes['value']));
  1797. } elseif ($attributes['value'] === false) {
  1798. $attributes['value'] = null;
  1799. }
  1800. $defaults = array('monthNames' => true);
  1801. $attributes = array_merge($defaults, (array) $attributes);
  1802. $monthNames = $attributes['monthNames'];
  1803. unset($attributes['monthNames']);
  1804. return $this->select(
  1805. $fieldName . ".month",
  1806. $this->_generateOptions('month', array('monthNames' => $monthNames)),
  1807. $attributes
  1808. );
  1809. }
  1810. /**
  1811. * Returns a SELECT element for hours.
  1812. *
  1813. * ### Attributes:
  1814. *
  1815. * - `empty` - If true, the empty select option is shown. If a string,
  1816. * that string is displayed as the empty element.
  1817. * - `value` The selected value of the input.
  1818. *
  1819. * @param string $fieldName Prefix name for the SELECT element
  1820. * @param boolean $format24Hours True for 24 hours format
  1821. * @param array $attributes List of HTML attributes
  1822. * @return string Completed hour select input
  1823. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hour
  1824. */
  1825. public function hour($fieldName, $format24Hours = false, $attributes = array()) {
  1826. $attributes += array('empty' => true, 'value' => null);
  1827. $attributes = $this->_dateTimeSelected('hour', $fieldName, $attributes);
  1828. if (strlen($attributes['value']) > 2) {
  1829. if ($format24Hours) {
  1830. $attributes['value'] = date('H', strtotime($attributes['value']));
  1831. } else {
  1832. $attributes['value'] = date('g', strtotime($attributes['value']));
  1833. }
  1834. } elseif ($attributes['value'] === false) {
  1835. $attributes['value'] = null;
  1836. }
  1837. return $this->select(
  1838. $fieldName . ".hour",
  1839. $this->_generateOptions($format24Hours ? 'hour24' : 'hour'),
  1840. $attributes
  1841. );
  1842. }
  1843. /**
  1844. * Returns a SELECT element for minutes.
  1845. *
  1846. * ### Attributes:
  1847. *
  1848. * - `empty` - If true, the empty select option is shown. If a string,
  1849. * that string is displayed as the empty element.
  1850. * - `value` The selected value of the input.
  1851. *
  1852. * @param string $fieldName Prefix name for the SELECT element
  1853. * @param string $attributes Array of Attributes
  1854. * @return string Completed minute select input.
  1855. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::minute
  1856. */
  1857. public function minute($fieldName, $attributes = array()) {
  1858. $attributes += array('empty' => true, 'value' => null);
  1859. $attributes = $this->_dateTimeSelected('min', $fieldName, $attributes);
  1860. if (strlen($attributes['value']) > 2) {
  1861. $attributes['value'] = date('i', strtotime($attributes['value']));
  1862. } elseif ($attributes['value'] === false) {
  1863. $attributes['value'] = null;
  1864. }
  1865. $minuteOptions = array();
  1866. if (isset($attributes['interval'])) {
  1867. $minuteOptions['interval'] = $attributes['interval'];
  1868. unset($attributes['interval']);
  1869. }
  1870. return $this->select(
  1871. $fieldName . ".min", $this->_generateOptions('minute', $minuteOptions),
  1872. $attributes
  1873. );
  1874. }
  1875. /**
  1876. * Selects values for dateTime selects.
  1877. *
  1878. * @param string $select Name of element field. ex. 'day'
  1879. * @param string $fieldName Name of fieldName being generated ex. Model.created
  1880. * @param array $attributes Array of attributes, must contain 'empty' key.
  1881. * @return array Attributes array with currently selected value.
  1882. */
  1883. protected function _dateTimeSelected($select, $fieldName, $attributes) {
  1884. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  1885. if (is_array($value) && isset($value[$select])) {
  1886. $attributes['value'] = $value[$select];
  1887. } else {
  1888. if (empty($value)) {
  1889. if (!$attributes['empty']) {
  1890. $attributes['value'] = 'now';
  1891. }
  1892. } else {
  1893. $attributes['value'] = $value;
  1894. }
  1895. }
  1896. }
  1897. return $attributes;
  1898. }
  1899. /**
  1900. * Returns a SELECT element for AM or PM.
  1901. *
  1902. * ### Attributes:
  1903. *
  1904. * - `empty` - If true, the empty select option is shown. If a string,
  1905. * that string is displayed as the empty element.
  1906. * - `value` The selected value of the input.
  1907. *
  1908. * @param string $fieldName Prefix name for the SELECT element
  1909. * @param string $attributes Array of Attributes
  1910. * @return string Completed meridian select input
  1911. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::meridian
  1912. */
  1913. public function meridian($fieldName, $attributes = array()) {
  1914. $attributes += array('empty' => true, 'value' => null);
  1915. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  1916. if (is_array($value)) {
  1917. extract($value);
  1918. $attributes['value'] = $meridian;
  1919. } else {
  1920. if (empty($value)) {
  1921. if (!$attributes['empty']) {
  1922. $attributes['value'] = date('a');
  1923. }
  1924. } else {
  1925. $attributes['value'] = date('a', strtotime($value));
  1926. }
  1927. }
  1928. }
  1929. if ($attributes['value'] === false) {
  1930. $attributes['value'] = null;
  1931. }
  1932. return $this->select(
  1933. $fieldName . ".meridian", $this->_generateOptions('meridian'),
  1934. $attributes
  1935. );
  1936. }
  1937. /**
  1938. * Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
  1939. *
  1940. * ### Attributes:
  1941. *
  1942. * - `monthNames` If false, 2 digit numbers will be used instead of text.
  1943. * If a array, the given array will be used.
  1944. * - `minYear` The lowest year to use in the year select
  1945. * - `maxYear` The maximum year to use in the year select
  1946. * - `interval` The interval for the minutes select. Defaults to 1
  1947. * - `separator` The contents of the string between select elements. Defaults to '-'
  1948. * - `empty` - If true, the empty select option is shown. If a string,
  1949. * that string is displayed as the empty element.
  1950. * - `value` | `default` The default value to be used by the input. A value in `$this->data`
  1951. * matching the field name will override this value. If no default is provided `time()` will be used.
  1952. *
  1953. * @param string $fieldName Prefix name for the SELECT element
  1954. * @param string $dateFormat DMY, MDY, YMD.
  1955. * @param string $timeFormat 12, 24.
  1956. * @param string $attributes array of Attributes
  1957. * @return string Generated set of select boxes for the date and time formats chosen.
  1958. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::dateTime
  1959. */
  1960. public function dateTime($fieldName, $dateFormat = 'DMY', $timeFormat = '12', $attributes = array()) {
  1961. $attributes += array('empty' => true, 'value' => null);
  1962. $year = $month = $day = $hour = $min = $meridian = null;
  1963. if (empty($attributes['value'])) {
  1964. $attributes = $this->value($attributes, $fieldName);
  1965. }
  1966. if ($attributes['value'] === null && $attributes['empty'] != true) {
  1967. $attributes['value'] = time();
  1968. }
  1969. if (!empty($attributes['value'])) {
  1970. if (is_array($attributes['value'])) {
  1971. extract($attributes['value']);
  1972. } else {
  1973. if (is_numeric($attributes['value'])) {
  1974. $attributes['value'] = strftime('%Y-%m-%d %H:%M:%S', $attributes['value']);
  1975. }
  1976. $meridian = 'am';
  1977. $pos = strpos($attributes['value'], '-');
  1978. if ($pos !== false) {
  1979. $date = explode('-', $attributes['value']);
  1980. $days = explode(' ', $date[2]);
  1981. $day = $days[0];
  1982. $month = $date[1];
  1983. $year = $date[0];
  1984. } else {
  1985. $days[1] = $attributes['value'];
  1986. }
  1987. if (!empty($timeFormat)) {
  1988. $time = explode(':', $days[1]);
  1989. if (($time[0] > 12) && $timeFormat == '12') {
  1990. $time[0] = $time[0] - 12;
  1991. $meridian = 'pm';
  1992. } elseif ($time[0] == '12' && $timeFormat == '12') {
  1993. $meridian = 'pm';
  1994. } elseif ($time[0] == '00' && $timeFormat == '12') {
  1995. $time[0] = 12;
  1996. } elseif ($time[0] >= 12) {
  1997. $meridian = 'pm';
  1998. }
  1999. if ($time[0] == 0 && $timeFormat == '12') {
  2000. $time[0] = 12;
  2001. }
  2002. $hour = $min = null;
  2003. if (isset($time[1])) {
  2004. $hour = $time[0];
  2005. $min = $time[1];
  2006. }
  2007. }
  2008. }
  2009. }
  2010. $elements = array('Day', 'Month', 'Year', 'Hour', 'Minute', 'Meridian');
  2011. $defaults = array(
  2012. 'minYear' => null, 'maxYear' => null, 'separator' => '-',
  2013. 'interval' => 1, 'monthNames' => true
  2014. );
  2015. $attributes = array_merge($defaults, (array) $attributes);
  2016. if (isset($attributes['minuteInterval'])) {
  2017. $attributes['interval'] = $attributes['minuteInterval'];
  2018. unset($attributes['minuteInterval']);
  2019. }
  2020. $minYear = $attributes['minYear'];
  2021. $maxYear = $attributes['maxYear'];
  2022. $separator = $attributes['separator'];
  2023. $interval = $attributes['interval'];
  2024. $monthNames = $attributes['monthNames'];
  2025. $attributes = array_diff_key($attributes, $defaults);
  2026. if (isset($attributes['id'])) {
  2027. if (is_string($attributes['id'])) {
  2028. // build out an array version
  2029. foreach ($elements as $element) {
  2030. $selectAttrName = 'select' . $element . 'Attr';
  2031. ${$selectAttrName} = $attributes;
  2032. ${$selectAttrName}['id'] = $attributes['id'] . $element;
  2033. }
  2034. } elseif (is_array($attributes['id'])) {
  2035. // check for missing ones and build selectAttr for each element
  2036. $attributes['id'] += array(
  2037. 'month' => '', 'year' => '', 'day' => '',
  2038. 'hour' => '', 'minute' => '', 'meridian' => ''
  2039. );
  2040. foreach ($elements as $element) {
  2041. $selectAttrName = 'select' . $element . 'Attr';
  2042. ${$selectAttrName} = $attributes;
  2043. ${$selectAttrName}['id'] = $attributes['id'][strtolower($element)];
  2044. }
  2045. }
  2046. } else {
  2047. // build the selectAttrName with empty id's to pass
  2048. foreach ($elements as $element) {
  2049. $selectAttrName = 'select' . $element . 'Attr';
  2050. ${$selectAttrName} = $attributes;
  2051. }
  2052. }
  2053. $selects = array();
  2054. foreach (preg_split('//', $dateFormat, -1, PREG_SPLIT_NO_EMPTY) as $char) {
  2055. switch ($char) {
  2056. case 'Y':
  2057. $selectYearAttr['value'] = $year;
  2058. $selects[] = $this->year(
  2059. $fieldName, $minYear, $maxYear, $selectYearAttr
  2060. );
  2061. break;
  2062. case 'M':
  2063. $selectMonthAttr['value'] = $month;
  2064. $selectMonthAttr['monthNames'] = $monthNames;
  2065. $selects[] = $this->month($fieldName, $selectMonthAttr);
  2066. break;
  2067. case 'D':
  2068. $selectDayAttr['value'] = $day;
  2069. $selects[] = $this->day($fieldName, $selectDayAttr);
  2070. break;
  2071. }
  2072. }
  2073. $opt = implode($separator, $selects);
  2074. if (!empty($interval) && $interval > 1 && !empty($min)) {
  2075. $min = round($min * (1 / $interval)) * $interval;
  2076. }
  2077. $selectMinuteAttr['interval'] = $interval;
  2078. switch ($timeFormat) {
  2079. case '24':
  2080. $selectHourAttr['value'] = $hour;
  2081. $selectMinuteAttr['value'] = $min;
  2082. $opt .= $this->hour($fieldName, true, $selectHourAttr) . ':' .
  2083. $this->minute($fieldName, $selectMinuteAttr);
  2084. break;
  2085. case '12':
  2086. $selectHourAttr['value'] = $hour;
  2087. $selectMinuteAttr['value'] = $min;
  2088. $selectMeridianAttr['value'] = $meridian;
  2089. $opt .= $this->hour($fieldName, false, $selectHourAttr) . ':' .
  2090. $this->minute($fieldName, $selectMinuteAttr) . ' ' .
  2091. $this->meridian($fieldName, $selectMeridianAttr);
  2092. break;
  2093. default:
  2094. $opt .= '';
  2095. break;
  2096. }
  2097. return $opt;
  2098. }
  2099. /**
  2100. * Gets the input field name for the current tag
  2101. *
  2102. * @param array $options
  2103. * @param string $field
  2104. * @param string $key
  2105. * @return array
  2106. */
  2107. protected function _name($options = array(), $field = null, $key = 'name') {
  2108. if ($this->requestType == 'get') {
  2109. if ($options === null) {
  2110. $options = array();
  2111. } elseif (is_string($options)) {
  2112. $field = $options;
  2113. $options = 0;
  2114. }
  2115. if (!empty($field)) {
  2116. $this->setEntity($field);
  2117. }
  2118. if (is_array($options) && isset($options[$key])) {
  2119. return $options;
  2120. }
  2121. $entity = $this->entity();
  2122. $model = $this->model();
  2123. $name = $model === $entity[0] && isset($entity[1]) ? $entity[1] : $entity[0];
  2124. $last = $entity[count($entity) - 1];
  2125. if (in_array($last, $this->_fieldSuffixes)) {
  2126. $name .= '[' . $last . ']';
  2127. }
  2128. if (is_array($options)) {
  2129. $options[$key] = $name;
  2130. return $options;
  2131. } else {
  2132. return $name;
  2133. }
  2134. }
  2135. return parent::_name($options, $field, $key);
  2136. }
  2137. /**
  2138. * Returns an array of formatted OPTION/OPTGROUP elements
  2139. *
  2140. * @param array $elements
  2141. * @param array $parents
  2142. * @param boolean $showParents
  2143. * @param array $attributes
  2144. * @return array
  2145. */
  2146. protected function _selectOptions($elements = array(), $parents = array(), $showParents = null, $attributes = array()) {
  2147. $select = array();
  2148. $attributes = array_merge(
  2149. array('escape' => true, 'style' => null, 'value' => null, 'class' => null),
  2150. $attributes
  2151. );
  2152. $selectedIsEmpty = ($attributes['value'] === '' || $attributes['value'] === null);
  2153. $selectedIsArray = is_array($attributes['value']);
  2154. foreach ($elements as $name => $title) {
  2155. $htmlOptions = array();
  2156. if (is_array($title) && (!isset($title['name']) || !isset($title['value']))) {
  2157. if (!empty($name)) {
  2158. if ($attributes['style'] === 'checkbox') {
  2159. $select[] = $this->Html->useTag('fieldsetend');
  2160. } else {
  2161. $select[] = $this->Html->useTag('optiongroupend');
  2162. }
  2163. $parents[] = $name;
  2164. }
  2165. $select = array_merge($select, $this->_selectOptions(
  2166. $title, $parents, $showParents, $attributes
  2167. ));
  2168. if (!empty($name)) {
  2169. $name = $attributes['escape'] ? h($name) : $name;
  2170. if ($attributes['style'] === 'checkbox') {
  2171. $select[] = $this->Html->useTag('fieldsetstart', $name);
  2172. } else {
  2173. $select[] = $this->Html->useTag('optiongroup', $name, '');
  2174. }
  2175. }
  2176. $name = null;
  2177. } elseif (is_array($title)) {
  2178. $htmlOptions = $title;
  2179. $name = $title['value'];
  2180. $title = $title['name'];
  2181. unset($htmlOptions['name'], $htmlOptions['value']);
  2182. }
  2183. if ($name !== null) {
  2184. if (
  2185. (!$selectedIsArray && !$selectedIsEmpty && (string)$attributes['value'] == (string)$name) ||
  2186. ($selectedIsArray && in_array($name, $attributes['value']))
  2187. ) {
  2188. if ($attributes['style'] === 'checkbox') {
  2189. $htmlOptions['checked'] = true;
  2190. } else {
  2191. $htmlOptions['selected'] = 'selected';
  2192. }
  2193. }
  2194. if ($showParents || (!in_array($title, $parents))) {
  2195. $title = ($attributes['escape']) ? h($title) : $title;
  2196. if ($attributes['style'] === 'checkbox') {
  2197. $htmlOptions['value'] = $name;
  2198. $tagName = $attributes['id'] . Inflector::camelize(Inflector::slug($name));
  2199. $htmlOptions['id'] = $tagName;
  2200. $label = array('for' => $tagName);
  2201. if (isset($htmlOptions['checked']) && $htmlOptions['checked'] === true) {
  2202. $label['class'] = 'selected';
  2203. }
  2204. $name = $attributes['name'];
  2205. if (empty($attributes['class'])) {
  2206. $attributes['class'] = 'checkbox';
  2207. } elseif ($attributes['class'] === 'form-error') {
  2208. $attributes['class'] = 'checkbox ' . $attributes['class'];
  2209. }
  2210. $label = $this->label(null, $title, $label);
  2211. $item = $this->Html->useTag('checkboxmultiple', $name, $htmlOptions);
  2212. $select[] = $this->Html->div($attributes['class'], $item . $label);
  2213. } else {
  2214. $select[] = $this->Html->useTag('selectoption', $name, $htmlOptions, $title);
  2215. }
  2216. }
  2217. }
  2218. }
  2219. return array_reverse($select, true);
  2220. }
  2221. /**
  2222. * Generates option lists for common <select /> menus
  2223. *
  2224. * @param string $name
  2225. * @param array $options
  2226. * @return array
  2227. */
  2228. protected function _generateOptions($name, $options = array()) {
  2229. if (!empty($this->options[$name])) {
  2230. return $this->options[$name];
  2231. }
  2232. $data = array();
  2233. switch ($name) {
  2234. case 'minute':
  2235. if (isset($options['interval'])) {
  2236. $interval = $options['interval'];
  2237. } else {
  2238. $interval = 1;
  2239. }
  2240. $i = 0;
  2241. while ($i < 60) {
  2242. $data[sprintf('%02d', $i)] = sprintf('%02d', $i);
  2243. $i += $interval;
  2244. }
  2245. break;
  2246. case 'hour':
  2247. for ($i = 1; $i <= 12; $i++) {
  2248. $data[sprintf('%02d', $i)] = $i;
  2249. }
  2250. break;
  2251. case 'hour24':
  2252. for ($i = 0; $i <= 23; $i++) {
  2253. $data[sprintf('%02d', $i)] = $i;
  2254. }
  2255. break;
  2256. case 'meridian':
  2257. $data = array('am' => 'am', 'pm' => 'pm');
  2258. break;
  2259. case 'day':
  2260. $min = 1;
  2261. $max = 31;
  2262. if (isset($options['min'])) {
  2263. $min = $options['min'];
  2264. }
  2265. if (isset($options['max'])) {
  2266. $max = $options['max'];
  2267. }
  2268. for ($i = $min; $i <= $max; $i++) {
  2269. $data[sprintf('%02d', $i)] = $i;
  2270. }
  2271. break;
  2272. case 'month':
  2273. if ($options['monthNames'] === true) {
  2274. $data['01'] = __d('cake', 'January');
  2275. $data['02'] = __d('cake', 'February');
  2276. $data['03'] = __d('cake', 'March');
  2277. $data['04'] = __d('cake', 'April');
  2278. $data['05'] = __d('cake', 'May');
  2279. $data['06'] = __d('cake', 'June');
  2280. $data['07'] = __d('cake', 'July');
  2281. $data['08'] = __d('cake', 'August');
  2282. $data['09'] = __d('cake', 'September');
  2283. $data['10'] = __d('cake', 'October');
  2284. $data['11'] = __d('cake', 'November');
  2285. $data['12'] = __d('cake', 'December');
  2286. } else if (is_array($options['monthNames'])) {
  2287. $data = $options['monthNames'];
  2288. } else {
  2289. for ($m = 1; $m <= 12; $m++) {
  2290. $data[sprintf("%02s", $m)] = strftime("%m", mktime(1, 1, 1, $m, 1, 1999));
  2291. }
  2292. }
  2293. break;
  2294. case 'year':
  2295. $current = intval(date('Y'));
  2296. $min = !isset($options['min']) ? $current - 20 : (int)$options['min'];
  2297. $max = !isset($options['max']) ? $current + 20 : (int)$options['max'];
  2298. if ($min > $max) {
  2299. list($min, $max) = array($max, $min);
  2300. }
  2301. for ($i = $min; $i <= $max; $i++) {
  2302. $data[$i] = $i;
  2303. }
  2304. if ($options['order'] != 'asc') {
  2305. $data = array_reverse($data, true);
  2306. }
  2307. break;
  2308. }
  2309. $this->_options[$name] = $data;
  2310. return $this->_options[$name];
  2311. }
  2312. /**
  2313. * Sets field defaults and adds field to form security input hash
  2314. *
  2315. * ### Options
  2316. *
  2317. * - `secure` - boolean whether or not the field should be added to the security fields.
  2318. *
  2319. * @param string $field Name of the field to initialize options for.
  2320. * @param array $options Array of options to append options into.
  2321. * @return array Array of options for the input.
  2322. */
  2323. protected function _initInputField($field, $options = array()) {
  2324. if (isset($options['secure'])) {
  2325. $secure = $options['secure'];
  2326. unset($options['secure']);
  2327. } else {
  2328. $secure = (isset($this->request['_Token']) && !empty($this->request['_Token']));
  2329. }
  2330. $result = parent::_initInputField($field, $options);
  2331. if ($this->tagIsInvalid() !== false) {
  2332. $result = $this->addClass($result, 'form-error');
  2333. }
  2334. if ($secure === self::SECURE_SKIP) {
  2335. return $result;
  2336. }
  2337. $fieldName = null;
  2338. if (!empty($options['name'])) {
  2339. preg_match_all('/\[(.*?)\]/', $options['name'], $matches);
  2340. if (isset($matches[1])) {
  2341. $fieldName = $matches[1];
  2342. }
  2343. }
  2344. $this->_secure($secure, $fieldName);
  2345. return $result;
  2346. }
  2347. }