PageRenderTime 65ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/code/ryzom/tools/server/www/webtt/cake/libs/view/helpers/form.php

https://bitbucket.org/SirCotare/ryzom
PHP | 2215 lines | 1438 code | 181 blank | 596 comment | 360 complexity | 1be4d6b4dbf86a025b169872bc5b065c MD5 | raw file
Possible License(s): AGPL-3.0, GPL-3.0, LGPL-2.1
  1. <?php
  2. /**
  3. * Automatic generation of HTML FORMs from given data.
  4. *
  5. * Used for scaffolding.
  6. *
  7. * PHP versions 4 and 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2005-2010, 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-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package cake
  18. * @subpackage cake.cake.libs.view.helpers
  19. * @since CakePHP(tm) v 0.10.0.1076
  20. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  21. */
  22. /**
  23. * Form helper library.
  24. *
  25. * Automatic generation of HTML FORMs from given data.
  26. *
  27. * @package cake
  28. * @subpackage cake.cake.libs.view.helpers
  29. * @link http://book.cakephp.org/view/1383/Form
  30. */
  31. class FormHelper extends AppHelper {
  32. /**
  33. * Other helpers used by FormHelper
  34. *
  35. * @var array
  36. * @access public
  37. */
  38. var $helpers = array('Html');
  39. /**
  40. * Holds the fields array('field_name' => array('type'=> 'string', 'length'=> 100),
  41. * primaryKey and validates array('field_name')
  42. *
  43. * @access public
  44. */
  45. var $fieldset = array();
  46. /**
  47. * Options used by DateTime fields
  48. *
  49. * @var array
  50. */
  51. var $__options = array(
  52. 'day' => array(), 'minute' => array(), 'hour' => array(),
  53. 'month' => array(), 'year' => array(), 'meridian' => array()
  54. );
  55. /**
  56. * List of fields created, used with secure forms.
  57. *
  58. * @var array
  59. * @access public
  60. */
  61. var $fields = array();
  62. /**
  63. * Defines the type of form being created. Set by FormHelper::create().
  64. *
  65. * @var string
  66. * @access public
  67. */
  68. var $requestType = null;
  69. /**
  70. * The default model being used for the current form.
  71. *
  72. * @var string
  73. * @access public
  74. */
  75. var $defaultModel = null;
  76. /**
  77. * Persistent default options used by input(). Set by FormHelper::create().
  78. *
  79. * @var array
  80. * @access protected
  81. */
  82. var $_inputDefaults = array();
  83. /**
  84. * Introspects model information and extracts information related
  85. * to validation, field length and field type. Appends information into
  86. * $this->fieldset.
  87. *
  88. * @return Model Returns a model instance
  89. * @access protected
  90. */
  91. function &_introspectModel($model) {
  92. $object = null;
  93. if (is_string($model) && strpos($model, '.') !== false) {
  94. $path = explode('.', $model);
  95. $model = end($path);
  96. }
  97. if (ClassRegistry::isKeySet($model)) {
  98. $object =& ClassRegistry::getObject($model);
  99. }
  100. if (!empty($object)) {
  101. $fields = $object->schema();
  102. foreach ($fields as $key => $value) {
  103. unset($fields[$key]);
  104. $fields[$key] = $value;
  105. }
  106. if (!empty($object->hasAndBelongsToMany)) {
  107. foreach ($object->hasAndBelongsToMany as $alias => $assocData) {
  108. $fields[$alias] = array('type' => 'multiple');
  109. }
  110. }
  111. $validates = array();
  112. if (!empty($object->validate)) {
  113. foreach ($object->validate as $validateField => $validateProperties) {
  114. if ($this->_isRequiredField($validateProperties)) {
  115. $validates[] = $validateField;
  116. }
  117. }
  118. }
  119. $defaults = array('fields' => array(), 'key' => 'id', 'validates' => array());
  120. $key = $object->primaryKey;
  121. $this->fieldset[$model] = array_merge($defaults, compact('fields', 'key', 'validates'));
  122. }
  123. return $object;
  124. }
  125. /**
  126. * Returns if a field is required to be filled based on validation properties from the validating object
  127. *
  128. * @return boolean true if field is required to be filled, false otherwise
  129. * @access protected
  130. */
  131. function _isRequiredField($validateProperties) {
  132. $required = false;
  133. if (is_array($validateProperties)) {
  134. $dims = Set::countDim($validateProperties);
  135. if ($dims == 1 || ($dims == 2 && isset($validateProperties['rule']))) {
  136. $validateProperties = array($validateProperties);
  137. }
  138. foreach ($validateProperties as $rule => $validateProp) {
  139. if (isset($validateProp['allowEmpty']) && $validateProp['allowEmpty'] === true) {
  140. return false;
  141. }
  142. $rule = isset($validateProp['rule']) ? $validateProp['rule'] : false;
  143. $required = $rule || empty($validateProp);
  144. if ($required) {
  145. break;
  146. }
  147. }
  148. }
  149. return $required;
  150. }
  151. /**
  152. * Returns an HTML FORM element.
  153. *
  154. * ### Options:
  155. *
  156. * - `type` Form method defaults to POST
  157. * - `action` The controller action the form submits to, (optional).
  158. * - `url` The url the form submits to. Can be a string or a url array,
  159. * - `default` Allows for the creation of Ajax forms.
  160. * - `onsubmit` Used in conjunction with 'default' to create ajax forms.
  161. * - `inputDefaults` set the default $options for FormHelper::input(). Any options that would
  162. * be set when using FormHelper::input() can be set here. Options set with `inputDefaults`
  163. * can be overridden when calling input()
  164. * - `encoding` Set the accept-charset encoding for the form. Defaults to `Configure::read('App.encoding')`
  165. *
  166. * @access public
  167. * @param string $model The model object which the form is being defined for
  168. * @param array $options An array of html attributes and options.
  169. * @return string An formatted opening FORM tag.
  170. * @link http://book.cakephp.org/view/1384/Creating-Forms
  171. */
  172. function create($model = null, $options = array()) {
  173. $created = $id = false;
  174. $append = '';
  175. $view =& ClassRegistry::getObject('view');
  176. if (is_array($model) && empty($options)) {
  177. $options = $model;
  178. $model = null;
  179. }
  180. if (empty($model) && $model !== false && !empty($this->params['models'])) {
  181. $model = $this->params['models'][0];
  182. $this->defaultModel = $this->params['models'][0];
  183. } elseif (empty($model) && empty($this->params['models'])) {
  184. $model = false;
  185. }
  186. $models = ClassRegistry::keys();
  187. foreach ($models as $currentModel) {
  188. if (ClassRegistry::isKeySet($currentModel)) {
  189. $currentObject =& ClassRegistry::getObject($currentModel);
  190. if (is_a($currentObject, 'Model') && !empty($currentObject->validationErrors)) {
  191. $this->validationErrors[Inflector::camelize($currentModel)] =& $currentObject->validationErrors;
  192. }
  193. }
  194. }
  195. $object = $this->_introspectModel($model);
  196. $this->setEntity($model . '.', true);
  197. $modelEntity = $this->model();
  198. if (isset($this->fieldset[$modelEntity]['key'])) {
  199. $data = $this->fieldset[$modelEntity];
  200. $recordExists = (
  201. isset($this->data[$model]) &&
  202. !empty($this->data[$model][$data['key']]) &&
  203. !is_array($this->data[$model][$data['key']])
  204. );
  205. if ($recordExists) {
  206. $created = true;
  207. $id = $this->data[$model][$data['key']];
  208. }
  209. }
  210. $options = array_merge(array(
  211. 'type' => ($created && empty($options['action'])) ? 'put' : 'post',
  212. 'action' => null,
  213. 'url' => null,
  214. 'default' => true,
  215. 'encoding' => strtolower(Configure::read('App.encoding')),
  216. 'inputDefaults' => array()),
  217. $options);
  218. $this->_inputDefaults = $options['inputDefaults'];
  219. unset($options['inputDefaults']);
  220. if (empty($options['url']) || is_array($options['url'])) {
  221. if (empty($options['url']['controller'])) {
  222. if (!empty($model) && $model != $this->defaultModel) {
  223. $options['url']['controller'] = Inflector::underscore(Inflector::pluralize($model));
  224. } elseif (!empty($this->params['controller'])) {
  225. $options['url']['controller'] = Inflector::underscore($this->params['controller']);
  226. }
  227. }
  228. if (empty($options['action'])) {
  229. $options['action'] = $this->params['action'];
  230. }
  231. $actionDefaults = array(
  232. 'plugin' => $this->plugin,
  233. 'controller' => $view->viewPath,
  234. 'action' => $options['action']
  235. );
  236. if (!empty($options['action']) && !isset($options['id'])) {
  237. $options['id'] = $this->domId($options['action'] . 'Form');
  238. }
  239. $options['action'] = array_merge($actionDefaults, (array)$options['url']);
  240. if (empty($options['action'][0])) {
  241. $options['action'][0] = $id;
  242. }
  243. } elseif (is_string($options['url'])) {
  244. $options['action'] = $options['url'];
  245. }
  246. unset($options['url']);
  247. switch (strtolower($options['type'])) {
  248. case 'get':
  249. $htmlAttributes['method'] = 'get';
  250. break;
  251. case 'file':
  252. $htmlAttributes['enctype'] = 'multipart/form-data';
  253. $options['type'] = ($created) ? 'put' : 'post';
  254. case 'post':
  255. case 'put':
  256. case 'delete':
  257. $append .= $this->hidden('_method', array(
  258. 'name' => '_method', 'value' => strtoupper($options['type']), 'id' => null
  259. ));
  260. default:
  261. $htmlAttributes['method'] = 'post';
  262. break;
  263. }
  264. $this->requestType = strtolower($options['type']);
  265. $htmlAttributes['action'] = $this->url($options['action']);
  266. unset($options['type'], $options['action']);
  267. if ($options['default'] == false) {
  268. if (isset($htmlAttributes['onSubmit']) || isset($htmlAttributes['onsubmit'])) {
  269. $htmlAttributes['onsubmit'] .= ' event.returnValue = false; return false;';
  270. } else {
  271. $htmlAttributes['onsubmit'] = 'event.returnValue = false; return false;';
  272. }
  273. }
  274. if (!empty($options['encoding'])) {
  275. $htmlAttributes['accept-charset'] = $options['encoding'];
  276. unset($options['encoding']);
  277. }
  278. unset($options['default']);
  279. $htmlAttributes = array_merge($options, $htmlAttributes);
  280. $this->fields = array();
  281. if (isset($this->params['_Token']) && !empty($this->params['_Token'])) {
  282. $append .= $this->hidden('_Token.key', array(
  283. 'value' => $this->params['_Token']['key'], 'id' => 'Token' . mt_rand())
  284. );
  285. }
  286. if (!empty($append)) {
  287. $append = sprintf($this->Html->tags['block'], ' style="display:none;"', $append);
  288. }
  289. $this->setEntity($model . '.', true);
  290. $attributes = $this->_parseAttributes($htmlAttributes, null, '');
  291. return sprintf($this->Html->tags['form'], $attributes) . $append;
  292. }
  293. /**
  294. * Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden
  295. * input fields where appropriate.
  296. *
  297. * If $options is set a form submit button will be created. Options can be either a string or an array.
  298. *
  299. * {{{
  300. * array usage:
  301. *
  302. * array('label' => 'save'); value="save"
  303. * array('label' => 'save', 'name' => 'Whatever'); value="save" name="Whatever"
  304. * array('name' => 'Whatever'); value="Submit" name="Whatever"
  305. * array('label' => 'save', 'name' => 'Whatever', 'div' => 'good') <div class="good"> value="save" name="Whatever"
  306. * array('label' => 'save', 'name' => 'Whatever', 'div' => array('class' => 'good')); <div class="good"> value="save" name="Whatever"
  307. * }}}
  308. *
  309. * @param mixed $options as a string will use $options as the value of button,
  310. * @return string a closing FORM tag optional submit button.
  311. * @access public
  312. * @link http://book.cakephp.org/view/1389/Closing-the-Form
  313. */
  314. function end($options = null) {
  315. if (!empty($this->params['models'])) {
  316. $models = $this->params['models'][0];
  317. }
  318. $out = null;
  319. $submit = null;
  320. if ($options !== null) {
  321. $submitOptions = array();
  322. if (is_string($options)) {
  323. $submit = $options;
  324. } else {
  325. if (isset($options['label'])) {
  326. $submit = $options['label'];
  327. unset($options['label']);
  328. }
  329. $submitOptions = $options;
  330. }
  331. $out .= $this->submit($submit, $submitOptions);
  332. }
  333. if (isset($this->params['_Token']) && !empty($this->params['_Token'])) {
  334. $out .= $this->secure($this->fields);
  335. $this->fields = array();
  336. }
  337. $this->setEntity(null);
  338. $out .= $this->Html->tags['formend'];
  339. $view =& ClassRegistry::getObject('view');
  340. $view->modelScope = false;
  341. return $out;
  342. }
  343. /**
  344. * Generates a hidden field with a security hash based on the fields used in the form.
  345. *
  346. * @param array $fields The list of fields to use when generating the hash
  347. * @return string A hidden input field with a security hash
  348. * @access public
  349. */
  350. function secure($fields = array()) {
  351. if (!isset($this->params['_Token']) || empty($this->params['_Token'])) {
  352. return;
  353. }
  354. $locked = array();
  355. foreach ($fields as $key => $value) {
  356. if (!is_int($key)) {
  357. $locked[$key] = $value;
  358. unset($fields[$key]);
  359. }
  360. }
  361. sort($fields, SORT_STRING);
  362. ksort($locked, SORT_STRING);
  363. $fields += $locked;
  364. $fields = Security::hash(serialize($fields) . Configure::read('Security.salt'));
  365. $locked = implode(array_keys($locked), '|');
  366. $out = $this->hidden('_Token.fields', array(
  367. 'value' => urlencode($fields . ':' . $locked),
  368. 'id' => 'TokenFields' . mt_rand()
  369. ));
  370. $out = sprintf($this->Html->tags['block'], ' style="display:none;"', $out);
  371. return $out;
  372. }
  373. /**
  374. * Determine which fields of a form should be used for hash.
  375. * Populates $this->fields
  376. *
  377. * @param mixed $field Reference to field to be secured
  378. * @param mixed $value Field value, if value should not be tampered with.
  379. * @return void
  380. * @access private
  381. */
  382. function __secure($field = null, $value = null) {
  383. if (!$field) {
  384. $view =& ClassRegistry::getObject('view');
  385. $field = $view->entity();
  386. } elseif (is_string($field)) {
  387. $field = Set::filter(explode('.', $field), true);
  388. }
  389. if (!empty($this->params['_Token']['disabledFields'])) {
  390. foreach ((array)$this->params['_Token']['disabledFields'] as $disabled) {
  391. $disabled = explode('.', $disabled);
  392. if (array_values(array_intersect($field, $disabled)) === $disabled) {
  393. return;
  394. }
  395. }
  396. }
  397. $field = implode('.', $field);
  398. if (!in_array($field, $this->fields)) {
  399. if ($value !== null) {
  400. return $this->fields[$field] = $value;
  401. }
  402. $this->fields[] = $field;
  403. }
  404. }
  405. /**
  406. * Returns true if there is an error for the given field, otherwise false
  407. *
  408. * @param string $field This should be "Modelname.fieldname"
  409. * @return boolean If there are errors this method returns true, else false.
  410. * @access public
  411. * @link http://book.cakephp.org/view/1426/isFieldError
  412. */
  413. function isFieldError($field) {
  414. $this->setEntity($field);
  415. return (bool)$this->tagIsInvalid();
  416. }
  417. /**
  418. * Returns a formatted error message for given FORM field, NULL if no errors.
  419. *
  420. * ### Options:
  421. *
  422. * - `escape` bool Whether or not to html escape the contents of the error.
  423. * - `wrap` mixed Whether or not the error message should be wrapped in a div. If a
  424. * string, will be used as the HTML tag to use.
  425. * - `class` string The classname for the error message
  426. *
  427. * @param string $field A field name, like "Modelname.fieldname"
  428. * @param mixed $text Error message or array of $options. If array, `attributes` key
  429. * will get used as html attributes for error container
  430. * @param array $options Rendering options for <div /> wrapper tag
  431. * @return string If there are errors this method returns an error message, otherwise null.
  432. * @access public
  433. * @link http://book.cakephp.org/view/1423/error
  434. */
  435. function error($field, $text = null, $options = array()) {
  436. $defaults = array('wrap' => true, 'class' => 'error-message', 'escape' => true);
  437. $options = array_merge($defaults, $options);
  438. $this->setEntity($field);
  439. if ($error = $this->tagIsInvalid()) {
  440. if (is_array($error)) {
  441. list(,,$field) = explode('.', $field);
  442. if (isset($error[$field])) {
  443. $error = $error[$field];
  444. } else {
  445. return null;
  446. }
  447. }
  448. if (is_array($text) && is_numeric($error) && $error > 0) {
  449. $error--;
  450. }
  451. if (is_array($text)) {
  452. $options = array_merge($options, array_intersect_key($text, $defaults));
  453. if (isset($text['attributes']) && is_array($text['attributes'])) {
  454. $options = array_merge($options, $text['attributes']);
  455. }
  456. $text = isset($text[$error]) ? $text[$error] : null;
  457. unset($options[$error]);
  458. }
  459. if ($text != null) {
  460. $error = $text;
  461. } elseif (is_numeric($error)) {
  462. $error = sprintf(__('Error in field %s', true), Inflector::humanize($this->field()));
  463. }
  464. if ($options['escape']) {
  465. $error = h($error);
  466. unset($options['escape']);
  467. }
  468. if ($options['wrap']) {
  469. $tag = is_string($options['wrap']) ? $options['wrap'] : 'div';
  470. unset($options['wrap']);
  471. return $this->Html->tag($tag, $error, $options);
  472. } else {
  473. return $error;
  474. }
  475. } else {
  476. return null;
  477. }
  478. }
  479. /**
  480. * Returns a formatted LABEL element for HTML FORMs. Will automatically generate
  481. * a for attribute if one is not provided.
  482. *
  483. * @param string $fieldName This should be "Modelname.fieldname"
  484. * @param string $text Text that will appear in the label field.
  485. * @param mixed $options An array of HTML attributes, or a string, to be used as a class name.
  486. * @return string The formatted LABEL element
  487. * @link http://book.cakephp.org/view/1427/label
  488. */
  489. function label($fieldName = null, $text = null, $options = array()) {
  490. if (empty($fieldName)) {
  491. $view = ClassRegistry::getObject('view');
  492. $fieldName = implode('.', $view->entity());
  493. }
  494. if ($text === null) {
  495. if (strpos($fieldName, '.') !== false) {
  496. $text = array_pop(explode('.', $fieldName));
  497. } else {
  498. $text = $fieldName;
  499. }
  500. if (substr($text, -3) == '_id') {
  501. $text = substr($text, 0, strlen($text) - 3);
  502. }
  503. $text = __(Inflector::humanize(Inflector::underscore($text)), true);
  504. }
  505. if (is_string($options)) {
  506. $options = array('class' => $options);
  507. }
  508. if (isset($options['for'])) {
  509. $labelFor = $options['for'];
  510. unset($options['for']);
  511. } else {
  512. $labelFor = $this->domId($fieldName);
  513. }
  514. return sprintf(
  515. $this->Html->tags['label'],
  516. $labelFor,
  517. $this->_parseAttributes($options), $text
  518. );
  519. }
  520. /**
  521. * Generate a set of inputs for `$fields`. If $fields is null the current model
  522. * will be used.
  523. *
  524. * In addition to controller fields output, `$fields` can be used to control legend
  525. * and fieldset rendering with the `fieldset` and `legend` keys.
  526. * `$form->inputs(array('legend' => 'My legend'));` Would generate an input set with
  527. * a custom legend. You can customize individual inputs through `$fields` as well.
  528. *
  529. * {{{
  530. * $form->inputs(array(
  531. * 'name' => array('label' => 'custom label')
  532. * ));
  533. * }}}
  534. *
  535. * In addition to fields control, inputs() allows you to use a few additional options.
  536. *
  537. * - `fieldset` Set to false to disable the fieldset. If a string is supplied it will be used as
  538. * the classname for the fieldset element.
  539. * - `legend` Set to false to disable the legend for the generated input set. Or supply a string
  540. * to customize the legend text.
  541. *
  542. * @param mixed $fields An array of fields to generate inputs for, or null.
  543. * @param array $blacklist a simple array of fields to not create inputs for.
  544. * @return string Completed form inputs.
  545. * @access public
  546. */
  547. function inputs($fields = null, $blacklist = null) {
  548. $fieldset = $legend = true;
  549. $model = $this->model();
  550. if (is_array($fields)) {
  551. if (array_key_exists('legend', $fields)) {
  552. $legend = $fields['legend'];
  553. unset($fields['legend']);
  554. }
  555. if (isset($fields['fieldset'])) {
  556. $fieldset = $fields['fieldset'];
  557. unset($fields['fieldset']);
  558. }
  559. } elseif ($fields !== null) {
  560. $fieldset = $legend = $fields;
  561. if (!is_bool($fieldset)) {
  562. $fieldset = true;
  563. }
  564. $fields = array();
  565. }
  566. if (empty($fields)) {
  567. $fields = array_keys($this->fieldset[$model]['fields']);
  568. }
  569. if ($legend === true) {
  570. $actionName = __('New %s', true);
  571. $isEdit = (
  572. strpos($this->action, 'update') !== false ||
  573. strpos($this->action, 'edit') !== false
  574. );
  575. if ($isEdit) {
  576. $actionName = __('Edit %s', true);
  577. }
  578. $modelName = Inflector::humanize(Inflector::underscore($model));
  579. $legend = sprintf($actionName, __($modelName, true));
  580. }
  581. $out = null;
  582. foreach ($fields as $name => $options) {
  583. if (is_numeric($name) && !is_array($options)) {
  584. $name = $options;
  585. $options = array();
  586. }
  587. $entity = explode('.', $name);
  588. $blacklisted = (
  589. is_array($blacklist) &&
  590. (in_array($name, $blacklist) || in_array(end($entity), $blacklist))
  591. );
  592. if ($blacklisted) {
  593. continue;
  594. }
  595. $out .= $this->input($name, $options);
  596. }
  597. if (is_string($fieldset)) {
  598. $fieldsetClass = sprintf(' class="%s"', $fieldset);
  599. } else {
  600. $fieldsetClass = '';
  601. }
  602. if ($fieldset && $legend) {
  603. return sprintf(
  604. $this->Html->tags['fieldset'],
  605. $fieldsetClass,
  606. sprintf($this->Html->tags['legend'], $legend) . $out
  607. );
  608. } elseif ($fieldset) {
  609. return sprintf($this->Html->tags['fieldset'], $fieldsetClass, $out);
  610. } else {
  611. return $out;
  612. }
  613. }
  614. /**
  615. * Generates a form input element complete with label and wrapper div
  616. *
  617. * ### Options
  618. *
  619. * See each field type method for more information. Any options that are part of
  620. * $attributes or $options for the different **type** methods can be included in `$options` for input().i
  621. * Additionally, any unknown keys that are not in the list below, or part of the selected type's options
  622. * will be treated as a regular html attribute for the generated input.
  623. *
  624. * - `type` - Force the type of widget you want. e.g. `type => 'select'`
  625. * - `label` - Either a string label, or an array of options for the label. See FormHelper::label()
  626. * - `div` - Either `false` to disable the div, or an array of options for the div.
  627. * See HtmlHelper::div() for more options.
  628. * - `options` - for widgets that take options e.g. radio, select
  629. * - `error` - control the error message that is produced
  630. * - `empty` - String or boolean to enable empty select box options.
  631. * - `before` - Content to place before the label + input.
  632. * - `after` - Content to place after the label + input.
  633. * - `between` - Content to place between the label + input.
  634. * - `format` - format template for element order. Any element that is not in the array, will not be in the output.
  635. * - Default input format order: array('before', 'label', 'between', 'input', 'after', 'error')
  636. * - Default checkbox format order: array('before', 'input', 'between', 'label', 'after', 'error')
  637. * - Hidden input will not be formatted
  638. * - Radio buttons cannot have the order of input and label elements controlled with these settings.
  639. *
  640. * @param string $fieldName This should be "Modelname.fieldname"
  641. * @param array $options Each type of input takes different options.
  642. * @return string Completed form widget.
  643. * @access public
  644. * @link http://book.cakephp.org/view/1390/Automagic-Form-Elements
  645. */
  646. function input($fieldName, $options = array()) {
  647. $this->setEntity($fieldName);
  648. $options = array_merge(
  649. array('before' => null, 'between' => null, 'after' => null, 'format' => null),
  650. $this->_inputDefaults,
  651. $options
  652. );
  653. $modelKey = $this->model();
  654. $fieldKey = $this->field();
  655. if (!isset($this->fieldset[$modelKey])) {
  656. $this->_introspectModel($modelKey);
  657. }
  658. if (!isset($options['type'])) {
  659. $magicType = true;
  660. $options['type'] = 'text';
  661. if (isset($options['options'])) {
  662. $options['type'] = 'select';
  663. } elseif (in_array($fieldKey, array('psword', 'passwd', 'password'))) {
  664. $options['type'] = 'password';
  665. } elseif (isset($this->fieldset[$modelKey]['fields'][$fieldKey])) {
  666. $fieldDef = $this->fieldset[$modelKey]['fields'][$fieldKey];
  667. $type = $fieldDef['type'];
  668. $primaryKey = $this->fieldset[$modelKey]['key'];
  669. }
  670. if (isset($type)) {
  671. $map = array(
  672. 'string' => 'text', 'datetime' => 'datetime',
  673. 'boolean' => 'checkbox', 'timestamp' => 'datetime',
  674. 'text' => 'textarea', 'time' => 'time',
  675. 'date' => 'date', 'float' => 'text'
  676. );
  677. if (isset($this->map[$type])) {
  678. $options['type'] = $this->map[$type];
  679. } elseif (isset($map[$type])) {
  680. $options['type'] = $map[$type];
  681. }
  682. if ($fieldKey == $primaryKey) {
  683. $options['type'] = 'hidden';
  684. }
  685. }
  686. if (preg_match('/_id$/', $fieldKey) && $options['type'] !== 'hidden') {
  687. $options['type'] = 'select';
  688. }
  689. if ($modelKey === $fieldKey) {
  690. $options['type'] = 'select';
  691. if (!isset($options['multiple'])) {
  692. $options['multiple'] = 'multiple';
  693. }
  694. }
  695. }
  696. $types = array('checkbox', 'radio', 'select');
  697. if (
  698. (!isset($options['options']) && in_array($options['type'], $types)) ||
  699. (isset($magicType) && $options['type'] == 'text')
  700. ) {
  701. $view =& ClassRegistry::getObject('view');
  702. $varName = Inflector::variable(
  703. Inflector::pluralize(preg_replace('/_id$/', '', $fieldKey))
  704. );
  705. $varOptions = $view->getVar($varName);
  706. if (is_array($varOptions)) {
  707. if ($options['type'] !== 'radio') {
  708. $options['type'] = 'select';
  709. }
  710. $options['options'] = $varOptions;
  711. }
  712. }
  713. $autoLength = (!array_key_exists('maxlength', $options) && isset($fieldDef['length']));
  714. if ($autoLength && $options['type'] == 'text') {
  715. $options['maxlength'] = $fieldDef['length'];
  716. }
  717. if ($autoLength && $fieldDef['type'] == 'float') {
  718. $options['maxlength'] = array_sum(explode(',', $fieldDef['length']))+1;
  719. }
  720. $divOptions = array();
  721. $div = $this->_extractOption('div', $options, true);
  722. unset($options['div']);
  723. if (!empty($div)) {
  724. $divOptions['class'] = 'input';
  725. $divOptions = $this->addClass($divOptions, $options['type']);
  726. if (is_string($div)) {
  727. $divOptions['class'] = $div;
  728. } elseif (is_array($div)) {
  729. $divOptions = array_merge($divOptions, $div);
  730. }
  731. if (
  732. isset($this->fieldset[$modelKey]) &&
  733. in_array($fieldKey, $this->fieldset[$modelKey]['validates'])
  734. ) {
  735. $divOptions = $this->addClass($divOptions, 'required');
  736. }
  737. if (!isset($divOptions['tag'])) {
  738. $divOptions['tag'] = 'div';
  739. }
  740. }
  741. $label = null;
  742. if (isset($options['label']) && $options['type'] !== 'radio') {
  743. $label = $options['label'];
  744. unset($options['label']);
  745. }
  746. if ($options['type'] === 'radio') {
  747. $label = false;
  748. if (isset($options['options'])) {
  749. $radioOptions = (array)$options['options'];
  750. unset($options['options']);
  751. }
  752. }
  753. if ($label !== false) {
  754. $label = $this->_inputLabel($fieldName, $label, $options);
  755. }
  756. $error = $this->_extractOption('error', $options, null);
  757. unset($options['error']);
  758. $selected = $this->_extractOption('selected', $options, null);
  759. unset($options['selected']);
  760. if (isset($options['rows']) || isset($options['cols'])) {
  761. $options['type'] = 'textarea';
  762. }
  763. if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time' || $options['type'] === 'select') {
  764. $options += array('empty' => false);
  765. }
  766. if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time') {
  767. $dateFormat = $this->_extractOption('dateFormat', $options, 'MDY');
  768. $timeFormat = $this->_extractOption('timeFormat', $options, 12);
  769. unset($options['dateFormat'], $options['timeFormat']);
  770. }
  771. $type = $options['type'];
  772. $out = array_merge(
  773. array('before' => null, 'label' => null, 'between' => null, 'input' => null, 'after' => null, 'error' => null),
  774. array('before' => $options['before'], 'label' => $label, 'between' => $options['between'], 'after' => $options['after'])
  775. );
  776. $format = null;
  777. if (is_array($options['format']) && in_array('input', $options['format'])) {
  778. $format = $options['format'];
  779. }
  780. unset($options['type'], $options['before'], $options['between'], $options['after'], $options['format']);
  781. switch ($type) {
  782. case 'hidden':
  783. $input = $this->hidden($fieldName, $options);
  784. $format = array('input');
  785. unset($divOptions);
  786. break;
  787. case 'checkbox':
  788. $input = $this->checkbox($fieldName, $options);
  789. $format = $format ? $format : array('before', 'input', 'between', 'label', 'after', 'error');
  790. break;
  791. case 'radio':
  792. $input = $this->radio($fieldName, $radioOptions, $options);
  793. break;
  794. case 'text':
  795. case 'password':
  796. case 'file':
  797. $input = $this->{$type}($fieldName, $options);
  798. break;
  799. case 'select':
  800. $options += array('options' => array());
  801. $list = $options['options'];
  802. unset($options['options']);
  803. $input = $this->select($fieldName, $list, $selected, $options);
  804. break;
  805. case 'time':
  806. $input = $this->dateTime($fieldName, null, $timeFormat, $selected, $options);
  807. break;
  808. case 'date':
  809. $input = $this->dateTime($fieldName, $dateFormat, null, $selected, $options);
  810. break;
  811. case 'datetime':
  812. $input = $this->dateTime($fieldName, $dateFormat, $timeFormat, $selected, $options);
  813. break;
  814. case 'textarea':
  815. default:
  816. $input = $this->textarea($fieldName, $options + array('cols' => '30', 'rows' => '6'));
  817. break;
  818. }
  819. if ($type != 'hidden' && $error !== false) {
  820. $errMsg = $this->error($fieldName, $error);
  821. if ($errMsg) {
  822. $divOptions = $this->addClass($divOptions, 'error');
  823. $out['error'] = $errMsg;
  824. }
  825. }
  826. $out['input'] = $input;
  827. $format = $format ? $format : array('before', 'label', 'between', 'input', 'after', 'error');
  828. $output = '';
  829. foreach ($format as $element) {
  830. $output .= $out[$element];
  831. unset($out[$element]);
  832. }
  833. if (!empty($divOptions['tag'])) {
  834. $tag = $divOptions['tag'];
  835. unset($divOptions['tag']);
  836. $output = $this->Html->tag($tag, $output, $divOptions);
  837. }
  838. return $output;
  839. }
  840. /**
  841. * Extracts a single option from an options array.
  842. *
  843. * @param string $name The name of the option to pull out.
  844. * @param array $options The array of options you want to extract.
  845. * @param mixed $default The default option value
  846. * @return the contents of the option or default
  847. * @access protected
  848. */
  849. function _extractOption($name, $options, $default = null) {
  850. if (array_key_exists($name, $options)) {
  851. return $options[$name];
  852. }
  853. return $default;
  854. }
  855. /**
  856. * Generate a label for an input() call.
  857. *
  858. * @param array $options Options for the label element.
  859. * @return string Generated label element
  860. * @access protected
  861. */
  862. function _inputLabel($fieldName, $label, $options) {
  863. $labelAttributes = $this->domId(array(), 'for');
  864. if ($options['type'] === 'date' || $options['type'] === 'datetime') {
  865. if (isset($options['dateFormat']) && $options['dateFormat'] === 'NONE') {
  866. $labelAttributes['for'] .= 'Hour';
  867. $idKey = 'hour';
  868. } else {
  869. $labelAttributes['for'] .= 'Month';
  870. $idKey = 'month';
  871. }
  872. if (isset($options['id']) && isset($options['id'][$idKey])) {
  873. $labelAttributes['for'] = $options['id'][$idKey];
  874. }
  875. } elseif ($options['type'] === 'time') {
  876. $labelAttributes['for'] .= 'Hour';
  877. if (isset($options['id']) && isset($options['id']['hour'])) {
  878. $labelAttributes['for'] = $options['id']['hour'];
  879. }
  880. }
  881. if (is_array($label)) {
  882. $labelText = null;
  883. if (isset($label['text'])) {
  884. $labelText = $label['text'];
  885. unset($label['text']);
  886. }
  887. $labelAttributes = array_merge($labelAttributes, $label);
  888. } else {
  889. $labelText = $label;
  890. }
  891. if (isset($options['id']) && is_string($options['id'])) {
  892. $labelAttributes = array_merge($labelAttributes, array('for' => $options['id']));
  893. }
  894. return $this->label($fieldName, $labelText, $labelAttributes);
  895. }
  896. /**
  897. * Creates a checkbox input widget.
  898. *
  899. * ### Options:
  900. *
  901. * - `value` - the value of the checkbox
  902. * - `checked` - boolean indicate that this checkbox is checked.
  903. * - `hiddenField` - boolean to indicate if you want the results of checkbox() to include
  904. * a hidden input with a value of ''.
  905. * - `disabled` - create a disabled input.
  906. *
  907. * @param string $fieldName Name of a field, like this "Modelname.fieldname"
  908. * @param array $options Array of HTML attributes.
  909. * @return string An HTML text input element.
  910. * @access public
  911. * @link http://book.cakephp.org/view/1414/checkbox
  912. */
  913. function checkbox($fieldName, $options = array()) {
  914. $options = $this->_initInputField($fieldName, $options) + array('hiddenField' => true);
  915. $value = current($this->value());
  916. $output = "";
  917. if (empty($options['value'])) {
  918. $options['value'] = 1;
  919. } elseif (
  920. (!isset($options['checked']) && !empty($value) && $value === $options['value']) ||
  921. !empty($options['checked'])
  922. ) {
  923. $options['checked'] = 'checked';
  924. }
  925. if ($options['hiddenField']) {
  926. $hiddenOptions = array(
  927. 'id' => $options['id'] . '_', 'name' => $options['name'],
  928. 'value' => '0', 'secure' => false
  929. );
  930. if (isset($options['disabled']) && $options['disabled'] == true) {
  931. $hiddenOptions['disabled'] = 'disabled';
  932. }
  933. $output = $this->hidden($fieldName, $hiddenOptions);
  934. }
  935. unset($options['hiddenField']);
  936. return $output . sprintf(
  937. $this->Html->tags['checkbox'],
  938. $options['name'],
  939. $this->_parseAttributes($options, array('name'), null, ' ')
  940. );
  941. }
  942. /**
  943. * Creates a set of radio widgets. Will create a legend and fieldset
  944. * by default. Use $options to control this
  945. *
  946. * ### Attributes:
  947. *
  948. * - `separator` - define the string in between the radio buttons
  949. * - `legend` - control whether or not the widget set has a fieldset & legend
  950. * - `value` - indicate a value that is should be checked
  951. * - `label` - boolean to indicate whether or not labels for widgets show be displayed
  952. * - `hiddenField` - boolean to indicate if you want the results of radio() to include
  953. * a hidden input with a value of ''. This is useful for creating radio sets that non-continuous
  954. *
  955. * @param string $fieldName Name of a field, like this "Modelname.fieldname"
  956. * @param array $options Radio button options array.
  957. * @param array $attributes Array of HTML attributes, and special attributes above.
  958. * @return string Completed radio widget set.
  959. * @access public
  960. * @link http://book.cakephp.org/view/1429/radio
  961. */
  962. function radio($fieldName, $options = array(), $attributes = array()) {
  963. $attributes = $this->_initInputField($fieldName, $attributes);
  964. $legend = false;
  965. if (isset($attributes['legend'])) {
  966. $legend = $attributes['legend'];
  967. unset($attributes['legend']);
  968. } elseif (count($options) > 1) {
  969. $legend = __(Inflector::humanize($this->field()), true);
  970. }
  971. $label = true;
  972. if (isset($attributes['label'])) {
  973. $label = $attributes['label'];
  974. unset($attributes['label']);
  975. }
  976. $inbetween = null;
  977. if (isset($attributes['separator'])) {
  978. $inbetween = $attributes['separator'];
  979. unset($attributes['separator']);
  980. }
  981. if (isset($attributes['value'])) {
  982. $value = $attributes['value'];
  983. } else {
  984. $value = $this->value($fieldName);
  985. }
  986. $out = array();
  987. $hiddenField = isset($attributes['hiddenField']) ? $attributes['hiddenField'] : true;
  988. unset($attributes['hiddenField']);
  989. foreach ($options as $optValue => $optTitle) {
  990. $optionsHere = array('value' => $optValue);
  991. if (isset($value) && $optValue == $value) {
  992. $optionsHere['checked'] = 'checked';
  993. }
  994. $parsedOptions = $this->_parseAttributes(
  995. array_merge($attributes, $optionsHere),
  996. array('name', 'type', 'id'), '', ' '
  997. );
  998. $tagName = Inflector::camelize(
  999. $attributes['id'] . '_' . Inflector::slug($optValue)
  1000. );
  1001. if ($label) {
  1002. $optTitle = sprintf($this->Html->tags['label'], $tagName, null, $optTitle);
  1003. }
  1004. $out[] = sprintf(
  1005. $this->Html->tags['radio'], $attributes['name'],
  1006. $tagName, $parsedOptions, $optTitle
  1007. );
  1008. }
  1009. $hidden = null;
  1010. if ($hiddenField) {
  1011. if (!isset($value) || $value === '') {
  1012. $hidden = $this->hidden($fieldName, array(
  1013. 'id' => $attributes['id'] . '_', 'value' => '', 'name' => $attributes['name']
  1014. ));
  1015. }
  1016. }
  1017. $out = $hidden . implode($inbetween, $out);
  1018. if ($legend) {
  1019. $out = sprintf(
  1020. $this->Html->tags['fieldset'], '',
  1021. sprintf($this->Html->tags['legend'], $legend) . $out
  1022. );
  1023. }
  1024. return $out;
  1025. }
  1026. /**
  1027. * Creates a text input widget.
  1028. *
  1029. * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
  1030. * @param array $options Array of HTML attributes.
  1031. * @return string A generated HTML text input element
  1032. * @access public
  1033. * @link http://book.cakephp.org/view/1432/text
  1034. */
  1035. function text($fieldName, $options = array()) {
  1036. $options = $this->_initInputField($fieldName, array_merge(
  1037. array('type' => 'text'), $options
  1038. ));
  1039. return sprintf(
  1040. $this->Html->tags['input'],
  1041. $options['name'],
  1042. $this->_parseAttributes($options, array('name'), null, ' ')
  1043. );
  1044. }
  1045. /**
  1046. * Creates a password input widget.
  1047. *
  1048. * @param string $fieldName Name of a field, like in the form "Modelname.fieldname"
  1049. * @param array $options Array of HTML attributes.
  1050. * @return string A generated password input.
  1051. * @access public
  1052. * @link http://book.cakephp.org/view/1428/password
  1053. */
  1054. function password($fieldName, $options = array()) {
  1055. $options = $this->_initInputField($fieldName, $options);
  1056. return sprintf(
  1057. $this->Html->tags['password'],
  1058. $options['name'],
  1059. $this->_parseAttributes($options, array('name'), null, ' ')
  1060. );
  1061. }
  1062. /**
  1063. * Creates a textarea widget.
  1064. *
  1065. * ### Options:
  1066. *
  1067. * - `escape` - Whether or not the contents of the textarea should be escaped. Defaults to true.
  1068. *
  1069. * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
  1070. * @param array $options Array of HTML attributes, and special options above.
  1071. * @return string A generated HTML text input element
  1072. * @access public
  1073. * @link http://book.cakephp.org/view/1433/textarea
  1074. */
  1075. function textarea($fieldName, $options = array()) {
  1076. $options = $this->_initInputField($fieldName, $options);
  1077. $value = null;
  1078. if (array_key_exists('value', $options)) {
  1079. $value = $options['value'];
  1080. if (!array_key_exists('escape', $options) || $options['escape'] !== false) {
  1081. $value = h($value);
  1082. }
  1083. unset($options['value']);
  1084. }
  1085. return sprintf(
  1086. $this->Html->tags['textarea'],
  1087. $options['name'],
  1088. $this->_parseAttributes($options, array('type', 'name'), null, ' '),
  1089. $value
  1090. );
  1091. }
  1092. /**
  1093. * Creates a hidden input field.
  1094. *
  1095. * @param string $fieldName Name of a field, in the form of "Modelname.fieldname"
  1096. * @param array $options Array of HTML attributes.
  1097. * @return string A generated hidden input
  1098. * @access public
  1099. * @link http://book.cakephp.org/view/1425/hidden
  1100. */
  1101. function hidden($fieldName, $options = array()) {
  1102. $secure = true;
  1103. if (isset($options['secure'])) {
  1104. $secure = $options['secure'];
  1105. unset($options['secure']);
  1106. }
  1107. $options = $this->_initInputField($fieldName, array_merge(
  1108. $options, array('secure' => false)
  1109. ));
  1110. $model = $this->model();
  1111. if ($fieldName !== '_method' && $model !== '_Token' && $secure) {
  1112. $this->__secure(null, '' . $options['value']);
  1113. }
  1114. return sprintf(
  1115. $this->Html->tags['hidden'],
  1116. $options['name'],
  1117. $this->_parseAttributes($options, array('name', 'class'), '', ' ')
  1118. );
  1119. }
  1120. /**
  1121. * Creates file input widget.
  1122. *
  1123. * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
  1124. * @param array $options Array of HTML attributes.
  1125. * @return string A generated file input.
  1126. * @access public
  1127. * @link http://book.cakephp.org/view/1424/file
  1128. */
  1129. function file($fieldName, $options = array()) {
  1130. $options = array_merge($options, array('secure' => false));
  1131. $options = $this->_initInputField($fieldName, $options);
  1132. $view =& ClassRegistry::getObject('view');
  1133. $field = $view->entity();
  1134. foreach (array('name', 'type', 'tmp_name', 'error', 'size') as $suffix) {
  1135. $this->__secure(array_merge($field, array($suffix)));
  1136. }
  1137. $attributes = $this->_parseAttributes($options, array('name'), '', ' ');
  1138. return sprintf($this->Html->tags['file'], $options['name'], $attributes);
  1139. }
  1140. /**
  1141. * Creates a `<button>` tag. The type attribute defaults to `type="submit"`
  1142. * You can change it to a different value by using `$options['type']`.
  1143. *
  1144. * ### Options:
  1145. *
  1146. * - `escape` - HTML entity encode the $title of the button. Defaults to false.
  1147. *
  1148. * @param string $title The button's caption. Not automatically HTML encoded
  1149. * @param array $options Array of options and HTML attributes.
  1150. * @return string A HTML button tag.
  1151. * @access public
  1152. * @link http://book.cakephp.org/view/1415/button
  1153. */
  1154. function button($title, $options = array()) {
  1155. $options += array('type' => 'submit', 'escape' => false);
  1156. if ($options['escape']) {
  1157. $title = h($title);
  1158. }
  1159. return sprintf(
  1160. $this->Html->tags['button'],
  1161. $options['type'],
  1162. $this->_parseAttributes($options, array('type'), ' ', ''),
  1163. $title
  1164. );
  1165. }
  1166. /**
  1167. * Creates a submit button element. This method will generate `<input />` elements that
  1168. * can be used to submit, and reset forms by using $options. image submits can be created by supplying an
  1169. * image path for $caption.
  1170. *
  1171. * ### Options
  1172. *
  1173. * - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to
  1174. * FormHelper::input().
  1175. * - `before` - Content to include before the input.
  1176. * - `after` - Content to include after the input.
  1177. * - `type` - Set to 'reset' for reset inputs. Defaults to 'submit'
  1178. * - Other attributes will be assigned to the input element.
  1179. *
  1180. * ### Options
  1181. *
  1182. * - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to
  1183. * FormHelper::input().
  1184. * - Other attributes will be assigned to the input element.
  1185. *
  1186. * @param string $caption The label appearing on the button OR if string contains :// or the
  1187. * extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension
  1188. * exists, AND the first character is /, image is relative to webroot,
  1189. * OR if the first character is not /, image is relative to webroot/img.
  1190. * @param array $options Array of options. See above.
  1191. * @return string A HTML submit button
  1192. * @access public
  1193. * @link http://book.cakephp.org/view/1431/submit
  1194. */
  1195. function submit($caption = null, $options = array()) {
  1196. if (!is_string($caption) && empty($caption)) {
  1197. $caption = __('Submit', true);
  1198. }
  1199. $out = null;
  1200. $div = true;
  1201. if (isset($options['div'])) {
  1202. $div = $options['div'];
  1203. unset($options['div']);
  1204. }
  1205. $options += array('type' => 'submit', 'before' => null, 'after' => null);
  1206. $divOptions = array('tag' => 'div');
  1207. if ($div === true) {
  1208. $divOptions['class'] = 'submit';
  1209. } elseif ($div === false) {
  1210. unset($divOptions);
  1211. } elseif (is_string($div)) {
  1212. $divOptions['class'] = $div;
  1213. } elseif (is_array($div)) {
  1214. $divOptions = array_merge(array('class' => 'submit', 'tag' => 'div'), $div);
  1215. }
  1216. $before = $options['before'];
  1217. $after = $options['after'];
  1218. unset($options['before'], $options['after']);
  1219. if (strpos($caption, '://') !== false) {
  1220. unset($options['type']);
  1221. $out .= $before . sprintf(
  1222. $this->Html->tags['submitimage'],
  1223. $caption,
  1224. $this->_parseAttributes($options, null, '', ' ')
  1225. ) . $after;
  1226. } elseif (preg_match('/\.(jpg|jpe|jpeg|gif|png|ico)$/', $caption)) {
  1227. unset($options['type']);
  1228. if ($caption{0} !== '/') {
  1229. $url = $this->webroot(IMAGES_URL . $caption);
  1230. } else {
  1231. $caption = trim($caption, '/');
  1232. $url = $this->webroot($caption);
  1233. }
  1234. $out .= $before . sprintf(
  1235. $this->Html->tags['submitimage'],
  1236. $url,
  1237. $this->_parseAttributes($options, null, '', ' ')
  1238. ) . $after;
  1239. } else {
  1240. $options['value'] = $caption;
  1241. $out .= $before . sprintf(
  1242. $this->Html->tags['submit'],
  1243. $this->_parseAttributes($options, null, '', ' ')
  1244. ). $after;
  1245. }
  1246. if (isset($divOptions)) {
  1247. $tag = $divOptions['tag'];
  1248. unset($divOptions['tag']);
  1249. $out = $this->Html->tag($tag, $out, $divOptions);
  1250. }
  1251. return $out;
  1252. }
  1253. /**
  1254. * Returns a formatted SELECT element.
  1255. *
  1256. * ### Attributes:
  1257. *
  1258. * - `showParents` - If included in the array and set to true, an additional option element
  1259. * will be added for the parent of each option group. You can set an option with the same name
  1260. * and it's key will be used for the value of the option.
  1261. * - `multiple` - show a multiple select box. If set to 'checkbox' multiple checkboxes will be
  1262. * created instead.
  1263. * - `empty` - If true, the empty select option is shown. If a string,
  1264. * that string is displayed as the empty element.
  1265. * - `escape` - If true contents of options will be HTML entity encoded. Defaults to true.
  1266. * - `class` - When using multiple = checkbox the classname to apply to the divs. Defaults to 'checkbox'.
  1267. *
  1268. * ### Using options
  1269. *
  1270. * A simple array will create normal options:
  1271. *
  1272. * {{{
  1273. * $options = array(1 => 'one', 2 => 'two);
  1274. * $this->Form->select('Model.field', $options));
  1275. * }}}
  1276. *
  1277. * While a nested options array will create optgroups with options inside them.
  1278. * {{{
  1279. * $options = array(
  1280. * 1 => 'bill',
  1281. * 'fred' => array(
  1282. * 2 => 'fred',
  1283. * 3 => 'fred jr.'
  1284. * )
  1285. * );
  1286. * $this->Form->select('Model.field', $options);
  1287. * }}}
  1288. *
  1289. * In the above `2 => 'fred'` will not generate an option element. You should enable the `showParents`
  1290. * attribute to show the fred option.
  1291. *
  1292. * @param string $fieldName Name attribute of the SELECT
  1293. * @param array $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the
  1294. * SELECT element
  1295. * @param mixed $selected The option selected by default. If null, the default value
  1296. * from POST data will be used when available.
  1297. * @param array $attributes The HTML attributes of the select element.
  1298. * @return string Formatted SELECT element
  1299. * @access public
  1300. * @link http://book.cakephp.org/view/1430/select
  1301. */
  1302. function select($fieldName, $options = array(), $selected = null, $attributes = array()) {
  1303. $select = array();
  1304. $style = null;
  1305. $tag = null;
  1306. $attributes += array(
  1307. 'class' => null,
  1308. 'escape' => true,
  1309. 'secure' => null,
  1310. 'empty' => '',
  1311. 'showParents' => false,
  1312. 'hiddenField' => true
  1313. );
  1314. $escapeOptions = $this->_extractOption('escape', $attributes);
  1315. $secure = $this->_extractOption('secure', $attributes);
  1316. $showEmpty = $this->_extractOption('empty', $attributes);
  1317. $showParents = $this->_extractOption('showParents', $attributes);
  1318. $hiddenField = $this->_extractOption('hiddenField', $attributes);
  1319. unset($attributes['escape'], $attributes['secure'], $attributes['empty'], $attributes['showParents'], $attributes['hiddenField']);
  1320. $attributes = $this->_initInputField($fieldName, array_merge(
  1321. (array)$attributes, array('secure' => false)
  1322. ));
  1323. if (is_string($options) && isset($this->__options[$options])) {
  1324. $options = $this->__generateOptions($options);
  1325. } elseif (!is_array($options)) {
  1326. $options = array();
  1327. }
  1328. if (isset($attributes['type'])) {
  1329. unset($attributes['type']);
  1330. }
  1331. if (!isset($selected)) {
  1332. $selected = $attributes['value'];
  1333. }
  1334. if (!empty($attributes['multiple'])) {
  1335. $style = ($attributes['multiple'] === 'checkbox') ? 'checkbox' : null;
  1336. $template = ($style) ? 'checkboxmultiplestart' : 'selectmultiplestart';
  1337. $tag = $this->Html->tags[$template];
  1338. if ($hiddenField) {
  1339. $hiddenAttributes = array(
  1340. 'value' => '',
  1341. 'id' => $attributes['id'] . ($style ? '' : '_'),
  1342. 'secure' => false,
  1343. 'name' => $attributes['name']
  1344. );
  1345. $select[] = $this->hidden(null, $hiddenAttributes);
  1346. }
  1347. } else {
  1348. $tag = $this->Html->tags['selectstart'];
  1349. }
  1350. if (!empty($tag) || isset($template)) {
  1351. if (!isset($secure) || $secure == true) {
  1352. $this->__secure();
  1353. }
  1354. $select[] = sprintf($tag, $attributes['name'], $this->_parseAttributes(
  1355. $attributes, array('name', 'value'))
  1356. );
  1357. }
  1358. $emptyMulti = (
  1359. $showEmpty !== null && $showEmpty !== false && !(
  1360. empty($showEmpty) && (isset($attributes) &&
  1361. array_key_exists('multiple', $attributes))
  1362. )
  1363. );
  1364. if ($emptyMulti) {
  1365. $showEmpty = ($showEmpty === true) ? '' : $showEmpty;
  1366. $options = array_reverse($options, true);
  1367. $options[''] = $showEmpty;
  1368. $options = array_reverse($options, true);
  1369. }
  1370. $select = array_merge($select, $this->__selectOptions(
  1371. array_reverse($options, true),
  1372. $selected,
  1373. array(),
  1374. $showParents,
  1375. array('escape' => $escapeOptions, 'style' => $style, 'name' => $attributes['name'], 'class' => $attributes['class'])
  1376. ));
  1377. $template = ($style == 'checkbox') ? 'checkboxmultipleend' : 'selectend';
  1378. $select[] = $this->Html->tags[$template];
  1379. return implode("\n", $select);
  1380. }
  1381. /**
  1382. * Returns a SELECT element for days.
  1383. *
  1384. * ### Attributes:
  1385. *
  1386. * - `empty` - If true, the empty select option is shown. If a string,
  1387. * that string is displayed as the empty element.
  1388. *
  1389. * @param string $fieldName Prefix name for the SELECT element
  1390. * @param string $selected Option which is selected.
  1391. * @param array $attributes HTML attributes for the select element
  1392. * @return string A generated day select box.
  1393. * @access public
  1394. * @link http://book.cakephp.org/view/1419/day
  1395. */
  1396. function day($fieldName, $selected = null, $attributes = array()) {
  1397. $attributes += array('empty' => true);
  1398. $selected = $this->__dateTimeSelected('day', $fieldName, $selected, $attributes);
  1399. if (strlen($selected) > 2) {
  1400. $selected = date('d', strtotime($selected));
  1401. } elseif ($selected === false) {
  1402. $selected = null;
  1403. }
  1404. return $this->select($fieldName . ".day", $this->__generateOptions('day'), $selected, $attributes);
  1405. }
  1406. /**
  1407. * Returns a SELECT element for years
  1408. *
  1409. * ### Attributes:
  1410. *
  1411. * - `empty` - If true, the empty select option is shown. If a string,
  1412. * that string is displayed as the empty element.
  1413. * - `orderYear` - Ordering of year values in select options.
  1414. * Possible values 'asc', 'desc'. Default 'desc'
  1415. *
  1416. * @param string $fieldName Prefix name for the SELECT element
  1417. * @param integer $minYear First year in sequence
  1418. * @param integer $maxYear Last year in sequence
  1419. * @param string $selected Option which is selected.
  1420. * @param array $attributes Attribute array for the select elements.
  1421. * @return string Completed year select input
  1422. * @access public
  1423. * @link http://book.cakephp.org/view/1416/year
  1424. */
  1425. function year($fieldName, $minYear = null, $maxYear = null, $selected = null, $attributes = array()) {
  1426. $attributes += array('empty' => true);
  1427. if ((empty($selected) || $selected === true) && $value = $this->value($fieldName)) {
  1428. if (is_array($value)) {
  1429. extract($value);
  1430. $selected = $year;
  1431. } else {
  1432. if (empty($value)) {
  1433. if (!$attributes['empty'] && !$maxYear) {
  1434. $selected = 'now';
  1435. } elseif (!$attributes['empty'] && $maxYear && !$selected) {
  1436. $selected = $maxYear;
  1437. }
  1438. } else {
  1439. $selected = $value;
  1440. }
  1441. }
  1442. }
  1443. if (strlen($selected) > 4 || $selected === 'now') {
  1444. $selected = date('Y', strtotime($selected));
  1445. } elseif ($selected === false) {
  1446. $selected = null;
  1447. }
  1448. $yearOptions = array('min' => $minYear, 'max' => $maxYear, 'order' => 'desc');
  1449. if (isset($attributes['orderYear'])) {
  1450. $yearOptions['order'] = $attributes['orderYear'];
  1451. unset($attributes['orderYear']);
  1452. }
  1453. return $this->select(
  1454. $fieldName . '.year', $this->__generateOptions('year', $yearOptions),
  1455. $selected, $attributes
  1456. );
  1457. }
  1458. /**
  1459. * Returns a SELECT element for months.
  1460. *
  1461. * ### Attributes:
  1462. *
  1463. * - `monthNames` - If false, 2 digit numbers will be used instead of text.
  1464. * If a array, the given array will be used.
  1465. * - `empty` - If true, the empty select option is shown. If a string,
  1466. * that string is displayed as the empty element.
  1467. *
  1468. * @param string $fieldName Prefix name for the SELECT element
  1469. * @param string $selected Option which is selected.
  1470. * @param array $attributes Attributes for the select element
  1471. * @return string A generated month select dropdown.
  1472. * @access public
  1473. * @link http://book.cakephp.org/view/1417/month
  1474. */
  1475. function month($fieldName, $selected = null, $attributes = array()) {
  1476. $attributes += array('empty' => true);
  1477. $selected = $this->__dateTimeSelected('month', $fieldName, $selected, $attributes);
  1478. if (strlen($selected) > 2) {
  1479. $selected = date('m', strtotime($selected));
  1480. } elseif ($selected === false) {
  1481. $selected = null;
  1482. }
  1483. $defaults = array('monthNames' => true);
  1484. $attributes = array_merge($defaults, (array) $attributes);
  1485. $monthNames = $attributes['monthNames'];
  1486. unset($attributes['monthNames']);
  1487. return $this->select(
  1488. $fieldName . ".month",
  1489. $this->__generateOptions('month', array('monthNames' => $monthNames)),
  1490. $selected, $attributes
  1491. );
  1492. }
  1493. /**
  1494. * Returns a SELECT element for hours.
  1495. *
  1496. * ### Attributes:
  1497. *
  1498. * - `empty` - If true, the empty select option is shown. If a string,
  1499. * that string is displayed as the empty element.
  1500. *
  1501. * @param string $fieldName Prefix name for the SELECT element
  1502. * @param boolean $format24Hours True for 24 hours format
  1503. * @param string $selected Option which is selected.
  1504. * @param array $attributes List of HTML attributes
  1505. * @return string Completed hour select input
  1506. * @access public
  1507. * @link http://book.cakephp.org/view/1420/hour
  1508. */
  1509. function hour($fieldName, $format24Hours = false, $selected = null, $attributes = array()) {
  1510. $attributes += array('empty' => true);
  1511. $selected = $this->__dateTimeSelected('hour', $fieldName, $selected, $attributes);
  1512. if (strlen($selected) > 2) {
  1513. if ($format24Hours) {
  1514. $selected = date('H', strtotime($selected));
  1515. } else {
  1516. $selected = date('g', strtotime($selected));
  1517. }
  1518. } elseif ($selected === false) {
  1519. $selected = null;
  1520. }
  1521. return $this->select(
  1522. $fieldName . ".hour",
  1523. $this->__generateOptions($format24Hours ? 'hour24' : 'hour'),
  1524. $selected, $attributes
  1525. );
  1526. }
  1527. /**
  1528. * Returns a SELECT element for minutes.
  1529. *
  1530. * ### Attributes:
  1531. *
  1532. * - `empty` - If true, the empty select option is shown. If a string,
  1533. * that string is displayed as the empty element.
  1534. *
  1535. * @param string $fieldName Prefix name for the SELECT element
  1536. * @param string $selected Option which is selected.
  1537. * @param string $attributes Array of Attributes
  1538. * @return string Completed minute select input.
  1539. * @access public
  1540. * @link http://book.cakephp.org/view/1421/minute
  1541. */
  1542. function minute($fieldName, $selected = null, $attributes = array()) {
  1543. $attributes += array('empty' => true);
  1544. $selected = $this->__dateTimeSelected('min', $fieldName, $selected, $attributes);
  1545. if (strlen($selected) > 2) {
  1546. $selected = date('i', strtotime($selected));
  1547. } elseif ($selected === false) {
  1548. $selected = null;
  1549. }
  1550. $minuteOptions = array();
  1551. if (isset($attributes['interval'])) {
  1552. $minuteOptions['interval'] = $attributes['interval'];
  1553. unset($attributes['interval']);
  1554. }
  1555. return $this->select(
  1556. $fieldName . ".min", $this->__generateOptions('minute', $minuteOptions),
  1557. $selected, $attributes
  1558. );
  1559. }
  1560. /**
  1561. * Selects values for dateTime selects.
  1562. *
  1563. * @param string $select Name of element field. ex. 'day'
  1564. * @param string $fieldName Name of fieldName being generated ex. Model.created
  1565. * @param mixed $selected The current selected value.
  1566. * @param array $attributes Array of attributes, must contain 'empty' key.
  1567. * @return string Currently selected value.
  1568. * @access private
  1569. */
  1570. function __dateTimeSelected($select, $fieldName, $selected, $attributes) {
  1571. if ((empty($selected) || $selected === true) && $value = $this->value($fieldName)) {
  1572. if (is_array($value) && isset($value[$select])) {
  1573. $selected = $value[$select];
  1574. } else {
  1575. if (empty($value)) {
  1576. if (!$attributes['empty']) {
  1577. $selected = 'now';
  1578. }
  1579. } else {
  1580. $selected = $value;
  1581. }
  1582. }
  1583. }
  1584. return $selected;
  1585. }
  1586. /**
  1587. * Returns a SELECT element for AM or PM.
  1588. *
  1589. * ### Attributes:
  1590. *
  1591. * - `empty` - If true, the empty select option is shown. If a string,
  1592. * that string is displayed as the empty element.
  1593. *
  1594. * @param string $fieldName Prefix name for the SELECT element
  1595. * @param string $selected Option which is selected.
  1596. * @param string $attributes Array of Attributes
  1597. * @param bool $showEmpty Show/Hide an empty option
  1598. * @return string Completed meridian select input
  1599. * @access public
  1600. * @link http://book.cakephp.org/view/1422/meridian
  1601. */
  1602. function meridian($fieldName, $selected = null, $attributes = array()) {
  1603. $attributes += array('empty' => true);
  1604. if ((empty($selected) || $selected === true) && $value = $this->value($fieldName)) {
  1605. if (is_array($value)) {
  1606. extract($value);
  1607. $selected = $meridian;
  1608. } else {
  1609. if (empty($value)) {
  1610. if (!$attribues['empty']) {
  1611. $selected = date('a');
  1612. }
  1613. } else {
  1614. $selected = date('a', strtotime($value));
  1615. }
  1616. }
  1617. }
  1618. if ($selected === false) {
  1619. $selected = null;
  1620. }
  1621. return $this->select(
  1622. $fieldName . ".meridian", $this->__generateOptions('meridian'),
  1623. $selected, $attributes
  1624. );
  1625. }
  1626. /**
  1627. * Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
  1628. *
  1629. * ### Attributes:
  1630. *
  1631. * - `monthNames` If false, 2 digit numbers will be used instead of text.
  1632. * If a array, the given array will be used.
  1633. * - `minYear` The lowest year to use in the year select
  1634. * - `maxYear` The maximum year to use in the year select
  1635. * - `interval` The interval for the minutes select. Defaults to 1
  1636. * - `separator` The contents of the string between select elements. Defaults to '-'
  1637. * - `empty` - If true, the empty select option is shown. If a string,
  1638. * that string is displayed as the empty element.
  1639. * - `value` | `default` The default value to be used by the input. A value in `$this->data`
  1640. * matching the field name will override this value. If no default is provided `time()` will be used.
  1641. *
  1642. * @param string $fieldName Prefix name for the SELECT element
  1643. * @param string $dateFormat DMY, MDY, YMD.
  1644. * @param string $timeFormat 12, 24.
  1645. * @param string $selected Option which is selected.
  1646. * @param string $attributes array of Attributes
  1647. * @return string Generated set of select boxes for the date and time formats chosen.
  1648. * @access public
  1649. * @link http://book.cakephp.org/view/1418/dateTime
  1650. */
  1651. function dateTime($fieldName, $dateFormat = 'DMY', $timeFormat = '12', $selected = null, $attributes = array()) {
  1652. $attributes += array('empty' => true);
  1653. $year = $month = $day = $hour = $min = $meridian = null;
  1654. if (empty($selected)) {
  1655. $selected = $this->value($attributes, $fieldName);
  1656. if (isset($selected['value'])) {
  1657. $selected = $selected['value'];
  1658. } else {
  1659. $selected = null;
  1660. }
  1661. }
  1662. if ($selected === null && $attributes['empty'] != true) {
  1663. $selected = time();
  1664. }
  1665. if (!empty($selected)) {
  1666. if (is_array($selected)) {
  1667. extract($selected);
  1668. } else {
  1669. if (is_numeric($selected)) {
  1670. $selected = strftime('%Y-%m-%d %H:%M:%S', $selected);
  1671. }
  1672. $meridian = 'am';
  1673. $pos = strpos($selected, '-');
  1674. if ($pos !== false) {
  1675. $date = explode('-', $selected);
  1676. $days = explode(' ', $date[2]);
  1677. $day = $days[0];
  1678. $month = $date[1];
  1679. $year = $date[0];
  1680. } else {
  1681. $days[1] = $selected;
  1682. }
  1683. if (!empty($timeFormat)) {
  1684. $time = explode(':', $days[1]);
  1685. if (($time[0] > 12) && $timeFormat == '12') {
  1686. $time[0] = $time[0] - 12;
  1687. $meridian = 'pm';
  1688. } elseif ($time[0] == '00' && $timeFormat == '12') {
  1689. $time[0] = 12;
  1690. } elseif ($time[0] > 12) {
  1691. $meridian = 'pm';
  1692. }
  1693. if ($time[0] == 0 && $timeFormat == '12') {
  1694. $time[0] = 12;
  1695. }
  1696. $hour = $min = null;
  1697. if (isset($time[1])) {
  1698. $hour = $time[0];
  1699. $min = $time[1];
  1700. }
  1701. }
  1702. }
  1703. }
  1704. $elements = array('Day', 'Month', 'Year', 'Hour', 'Minute', 'Meridian');
  1705. $defaults = array(
  1706. 'minYear' => null, 'maxYear' => null, 'separator' => '-',
  1707. 'interval' => 1, 'monthNames' => true
  1708. );
  1709. $attributes = array_merge($defaults, (array) $attributes);
  1710. if (isset($attributes['minuteInterval'])) {
  1711. $attributes['interval'] = $attributes['minuteInterval'];
  1712. unset($attributes['minuteInterval']);
  1713. }
  1714. $minYear = $attributes['minYear'];
  1715. $maxYear = $attributes['maxYear'];
  1716. $separator = $attributes['separator'];
  1717. $interval = $attributes['interval'];
  1718. $monthNames = $attributes['monthNames'];
  1719. $attributes = array_diff_key($attributes, $defaults);
  1720. if (isset($attributes['id'])) {
  1721. if (is_string($attributes['id'])) {
  1722. // build out an array version
  1723. foreach ($elements as $element) {
  1724. $selectAttrName = 'select' . $element . 'Attr';
  1725. ${$selectAttrName} = $attributes;
  1726. ${$selectAttrName}['id'] = $attributes['id'] . $element;
  1727. }
  1728. } elseif (is_array($attributes['id'])) {
  1729. // check for missing ones and build selectAttr for each element
  1730. $attributes['id'] += array(
  1731. 'month' => '', 'year' => '', 'day' => '',
  1732. 'hour' => '', 'minute' => '', 'meridian' => ''
  1733. );
  1734. foreach ($elements as $element) {
  1735. $selectAttrName = 'select' . $element . 'Attr';
  1736. ${$selectAttrName} = $attributes;
  1737. ${$selectAttrName}['id'] = $attributes['id'][strtolower($element)];
  1738. }
  1739. }
  1740. } else {
  1741. // build the selectAttrName with empty id's to pass
  1742. foreach ($elements as $element) {
  1743. $selectAttrName = 'select' . $element . 'Attr';
  1744. ${$selectAttrName} = $attributes;
  1745. }
  1746. }
  1747. $selects = array();
  1748. foreach (preg_split('//', $dateFormat, -1, PREG_SPLIT_NO_EMPTY) as $char) {
  1749. switch ($char) {
  1750. case 'Y':
  1751. $selects[] = $this->year(
  1752. $fieldName, $minYear, $maxYear, $year, $selectYearAttr
  1753. );
  1754. break;
  1755. case 'M':
  1756. $selectMonthAttr['monthNames'] = $monthNames;
  1757. $selects[] = $this->month($fieldName, $month, $selectMonthAttr);
  1758. break;
  1759. case 'D':
  1760. $selects[] = $this->day($fieldName, $day, $selectDayAttr);
  1761. break;
  1762. }
  1763. }
  1764. $opt = implode($separator, $selects);
  1765. if (!empty($interval) && $interval > 1 && !empty($min)) {
  1766. $min = round($min * (1 / $interval)) * $interval;
  1767. }
  1768. $selectMinuteAttr['interval'] = $interval;
  1769. switch ($timeFormat) {
  1770. case '24':
  1771. $opt .= $this->hour($fieldName, true, $hour, $selectHourAttr) . ':' .
  1772. $this->minute($fieldName, $min, $selectMinuteAttr);
  1773. break;
  1774. case '12':
  1775. $opt .= $this->hour($fieldName, false, $hour, $selectHourAttr) . ':' .
  1776. $this->minute($fieldName, $min, $selectMinuteAttr) . ' ' .
  1777. $this->meridian($fieldName, $meridian, $selectMeridianAttr);
  1778. break;
  1779. default:
  1780. $opt .= '';
  1781. break;
  1782. }
  1783. return $opt;
  1784. }
  1785. /**
  1786. * Gets the input field name for the current tag
  1787. *
  1788. * @param array $options
  1789. * @param string $key
  1790. * @return array
  1791. * @access protected
  1792. */
  1793. function _name($options = array(), $field = null, $key = 'name') {
  1794. if ($this->requestType == 'get') {
  1795. if ($options === null) {
  1796. $options = array();
  1797. } elseif (is_string($options)) {
  1798. $field = $options;
  1799. $options = 0;
  1800. }
  1801. if (!empty($field)) {
  1802. $this->setEntity($field);
  1803. }
  1804. if (is_array($options) && isset($options[$key])) {
  1805. return $options;
  1806. }
  1807. $view = ClassRegistry::getObject('view');
  1808. $name = !empty($view->field) ? $view->field : $view->model;
  1809. if (!empty($view->fieldSuffix)) {
  1810. $name .= '[' . $view->fieldSuffix . ']';
  1811. }
  1812. if (is_array($options)) {
  1813. $options[$key] = $name;
  1814. return $options;
  1815. } else {
  1816. return $name;
  1817. }
  1818. }
  1819. return parent::_name($options, $field, $key);
  1820. }
  1821. /**
  1822. * Returns an array of formatted OPTION/OPTGROUP elements
  1823. * @access private
  1824. * @return array
  1825. */
  1826. function __selectOptions($elements = array(), $selected = null, $parents = array(), $showParents = null, $attributes = array()) {
  1827. $select = array();
  1828. $attributes = array_merge(array('escape' => true, 'style' => null, 'class' => null), $attributes);
  1829. $selectedIsEmpty = ($selected === '' || $selected === null);
  1830. $selectedIsArray = is_array($selected);
  1831. foreach ($elements as $name => $title) {
  1832. $htmlOptions = array();
  1833. if (is_array($title) && (!isset($title['name']) || !isset($title['value']))) {
  1834. if (!empty($name)) {
  1835. if ($attributes['style'] === 'checkbox') {
  1836. $select[] = $this->Html->tags['fieldsetend'];
  1837. } else {
  1838. $select[] = $this->Html->tags['optiongroupend'];
  1839. }
  1840. $parents[] = $name;
  1841. }
  1842. $select = array_merge($select, $this->__selectOptions(
  1843. $title, $selected, $parents, $showParents, $attributes
  1844. ));
  1845. if (!empty($name)) {
  1846. $name = $attributes['escape'] ? h($name) : $name;
  1847. if ($attributes['style'] === 'checkbox') {
  1848. $select[] = sprintf($this->Html->tags['fieldsetstart'], $name);
  1849. } else {
  1850. $select[] = sprintf($this->Html->tags['optiongroup'], $name, '');
  1851. }
  1852. }
  1853. $name = null;
  1854. } elseif (is_array($title)) {
  1855. $htmlOptions = $title;
  1856. $name = $title['value'];
  1857. $title = $title['name'];
  1858. unset($htmlOptions['name'], $htmlOptions['value']);
  1859. }
  1860. if ($name !== null) {
  1861. if (
  1862. (!$selectedIsArray && !$selectedIsEmpty && (string)$selected == (string)$name) ||
  1863. ($selectedIsArray && in_array($name, $selected))
  1864. ) {
  1865. if ($attributes['style'] === 'checkbox') {
  1866. $htmlOptions['checked'] = true;
  1867. } else {
  1868. $htmlOptions['selected'] = 'selected';
  1869. }
  1870. }
  1871. if ($showParents || (!in_array($title, $parents))) {
  1872. $title = ($attributes['escape']) ? h($title) : $title;
  1873. if ($attributes['style'] === 'checkbox') {
  1874. $htmlOptions['value'] = $name;
  1875. $tagName = Inflector::camelize(
  1876. $this->model() . '_' . $this->field().'_'.Inflector::slug($name)
  1877. );
  1878. $htmlOptions['id'] = $tagName;
  1879. $label = array('for' => $tagName);
  1880. if (isset($htmlOptions['checked']) && $htmlOptions['checked'] === true) {
  1881. $label['class'] = 'selected';
  1882. }
  1883. $name = $attributes['name'];
  1884. if (empty($attributes['class'])) {
  1885. $attributes['class'] = 'checkbox';
  1886. } elseif ($attributes['class'] === 'form-error') {
  1887. $attributes['class'] = 'checkbox ' . $attributes['class'];
  1888. }
  1889. $label = $this->label(null, $title, $label);
  1890. $item = sprintf(
  1891. $this->Html->tags['checkboxmultiple'], $name,
  1892. $this->_parseAttributes($htmlOptions)
  1893. );
  1894. $select[] = $this->Html->div($attributes['class'], $item . $label);
  1895. } else {
  1896. $select[] = sprintf(
  1897. $this->Html->tags['selectoption'],
  1898. $name, $this->_parseAttributes($htmlOptions), $title
  1899. );
  1900. }
  1901. }
  1902. }
  1903. }
  1904. return array_reverse($select, true);
  1905. }
  1906. /**
  1907. * Generates option lists for common <select /> menus
  1908. * @access private
  1909. */
  1910. function __generateOptions($name, $options = array()) {
  1911. if (!empty($this->options[$name])) {
  1912. return $this->options[$name];
  1913. }
  1914. $data = array();
  1915. switch ($name) {
  1916. case 'minute':
  1917. if (isset($options['interval'])) {
  1918. $interval = $options['interval'];
  1919. } else {
  1920. $interval = 1;
  1921. }
  1922. $i = 0;
  1923. while ($i < 60) {
  1924. $data[sprintf('%02d', $i)] = sprintf('%02d', $i);
  1925. $i += $interval;
  1926. }
  1927. break;
  1928. case 'hour':
  1929. for ($i = 1; $i <= 12; $i++) {
  1930. $data[sprintf('%02d', $i)] = $i;
  1931. }
  1932. break;
  1933. case 'hour24':
  1934. for ($i = 0; $i <= 23; $i++) {
  1935. $data[sprintf('%02d', $i)] = $i;
  1936. }
  1937. break;
  1938. case 'meridian':
  1939. $data = array('am' => 'am', 'pm' => 'pm');
  1940. break;
  1941. case 'day':
  1942. $min = 1;
  1943. $max = 31;
  1944. if (isset($options['min'])) {
  1945. $min = $options['min'];
  1946. }
  1947. if (isset($options['max'])) {
  1948. $max = $options['max'];
  1949. }
  1950. for ($i = $min; $i <= $max; $i++) {
  1951. $data[sprintf('%02d', $i)] = $i;
  1952. }
  1953. break;
  1954. case 'month':
  1955. if ($options['monthNames'] === true) {
  1956. $data['01'] = __('January', true);
  1957. $data['02'] = __('February', true);
  1958. $data['03'] = __('March', true);
  1959. $data['04'] = __('April', true);
  1960. $data['05'] = __('May', true);
  1961. $data['06'] = __('June', true);
  1962. $data['07'] = __('July', true);
  1963. $data['08'] = __('August', true);
  1964. $data['09'] = __('September', true);
  1965. $data['10'] = __('October', true);
  1966. $data['11'] = __('November', true);
  1967. $data['12'] = __('December', true);
  1968. } else if (is_array($options['monthNames'])) {
  1969. $data = $options['monthNames'];
  1970. } else {
  1971. for ($m = 1; $m <= 12; $m++) {
  1972. $data[sprintf("%02s", $m)] = strftime("%m", mktime(1, 1, 1, $m, 1, 1999));
  1973. }
  1974. }
  1975. break;
  1976. case 'year':
  1977. $current = intval(date('Y'));
  1978. if (!isset($options['min'])) {
  1979. $min = $current - 20;
  1980. } else {
  1981. $min = $options['min'];
  1982. }
  1983. if (!isset($options['max'])) {
  1984. $max = $current + 20;
  1985. } else {
  1986. $max = $options['max'];
  1987. }
  1988. if ($min > $max) {
  1989. list($min, $max) = array($max, $min);
  1990. }
  1991. for ($i = $min; $i <= $max; $i++) {
  1992. $data[$i] = $i;
  1993. }
  1994. if ($options['order'] != 'asc') {
  1995. $data = array_reverse($data, true);
  1996. }
  1997. break;
  1998. }
  1999. $this->__options[$name] = $data;
  2000. return $this->__options[$name];
  2001. }
  2002. /**
  2003. * Sets field defaults and adds field to form security input hash
  2004. *
  2005. * Options
  2006. *
  2007. * - `secure` - boolean whether or not the field should be added to the security fields.
  2008. *
  2009. * @param string $field Name of the field to initialize options for.
  2010. * @param array $options Array of options to append options into.
  2011. * @return array Array of options for the input.
  2012. * @access protected
  2013. */
  2014. function _initInputField($field, $options = array()) {
  2015. if (isset($options['secure'])) {
  2016. $secure = $options['secure'];
  2017. unset($options['secure']);
  2018. } else {
  2019. $secure = (isset($this->params['_Token']) && !empty($this->params['_Token']));
  2020. }
  2021. $fieldName = null;
  2022. if ($secure && !empty($options['name'])) {
  2023. preg_match_all('/\[(.*?)\]/', $options['name'], $matches);
  2024. if (isset($matches[1])) {
  2025. $fieldName = $matches[1];
  2026. }
  2027. }
  2028. $result = parent::_initInputField($field, $options);
  2029. if ($secure) {
  2030. $this->__secure($fieldName);
  2031. }
  2032. return $result;
  2033. }
  2034. }