PageRenderTime 60ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/mattraykowski/ryzomcore_demoshard
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

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

  1. <?php
  2. /**
  3. * Automatic generation of HTML FORMs from given data.
  4. *
  5. * Used for scaffolding.
  6. *
  7. * PHP 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->__generateOption

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