PageRenderTime 64ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/htdocs/lithium/0.9.9/libraries/lithium/template/helper/Form.php

http://github.com/pmjones/php-framework-benchmarks
PHP | 689 lines | 602 code | 9 blank | 78 comment | 5 complexity | 50d2b0b046d05f7777490003e269f3e9 MD5 | raw file
Possible License(s): LGPL-3.0, Apache-2.0, BSD-3-Clause, ISC, AGPL-3.0, LGPL-2.1
  1. <?php
  2. /**
  3. * Lithium: the most rad php framework
  4. *
  5. * @copyright Copyright 2010, Union of RAD (http://union-of-rad.org)
  6. * @license http://opensource.org/licenses/bsd-license.php The BSD License
  7. */
  8. namespace lithium\template\helper;
  9. use lithium\util\Set;
  10. use lithium\util\Inflector;
  11. use UnexpectedValueException;
  12. /**
  13. * A helper class to facilitate generating, processing and securing HTML forms. By default, `Form`
  14. * will simply generate HTML forms and widgets, but by creating a form with a _binding object_,
  15. * the helper can pre-fill form input values, render error messages, and introspect column types.
  16. *
  17. * For example, assuming you have created a `Post` model in your application:
  18. * {{{// In controller code:
  19. * use \app\models\Post;
  20. * $post = Post::find(1);
  21. * return compact('post');
  22. *
  23. * // In view code:
  24. * <?=$this->form->create($post); // Echoes a <form> tag and binds the helper to $post ?>
  25. * <?=$this->form->text('title'); // Echoes an <input /> element, pre-filled with $post's title ?>
  26. * <?=$this->form->submit('Update'); // Echoes a submit button with the title 'Update' ?>
  27. * <?=$this->form->end(); // Echoes a </form> tag & unbinds the form ?>
  28. * }}}
  29. */
  30. class Form extends \lithium\template\Helper {
  31. /**
  32. * String templates used by this helper.
  33. *
  34. * @var array
  35. */
  36. protected $_strings = array(
  37. 'button' => '<input type="{:type}"{:options} />',
  38. 'checkbox' => '<input type="checkbox" name="{:name}"{:options} />',
  39. 'checkbox-multi' => '<input type="checkbox" name="{:name}[]"{:options} />',
  40. 'checkbox-multi-end' => '',
  41. 'checkbox-multi-start' => '',
  42. 'error' => '<div{:options}>{:content}</div>',
  43. 'errors' => '{:content}',
  44. 'element' => '<input type="{:type}" name="{:name}"{:options} />',
  45. 'file' => '<input type="file" name="{:name}"{:options} />',
  46. 'form' => '<form action="{:url}"{:options}>{:append}',
  47. 'form-end' => '</form>',
  48. 'hidden' => '<input type="hidden" name="{:name}"{:options} />',
  49. 'field' => '<div{:wrap}>{:label}{:input}{:error}</div>',
  50. 'field-checkbox' => '<div{:wrap}>{:input}{:label}{:error}</div>',
  51. 'field-radio' => '<div{:wrap}>{:input}{:label}{:error}</div>',
  52. 'label' => '<label for="{:name}"{:options}>{:title}</label>',
  53. 'legend' => '<legend>{:content}</legend>',
  54. 'option-group' => '<optgroup label="{:label}"{:options}>',
  55. 'option-group-end' => '</optgroup>',
  56. 'password' => '<input type="password" name="{:name}"{:options} />',
  57. 'radio' => '<input type="radio" name="{:name}" {:options} />',
  58. 'select-start' => '<select name="{:name}"{:options}>',
  59. 'select-multi-start' => '<select name="{:name}[]"{:options}>',
  60. 'select-empty' => '<option value=""{:options}>&nbsp;</option>',
  61. 'select-option' => '<option value="{:value}"{:options}>{:title}</option>',
  62. 'select-end' => '</select>',
  63. 'submit' => '<input type="submit" value="{:title}"{:options} />',
  64. 'submit-image' => '<input type="image" src="{:url}"{:options} />',
  65. 'text' => '<input type="text" name="{:name}"{:options} />',
  66. 'textarea' => '<textarea name="{:name}"{:options}>{:value}</textarea>',
  67. 'fieldset' => '<fieldset{:options}>{:content}</fieldset>',
  68. 'fieldset-start' => '<fieldset><legend>{:content}</legend>',
  69. 'fieldset-end' => '</fieldset>'
  70. );
  71. /**
  72. * Maps method names to template string names, allowing the default template strings to be set
  73. * permanently on a per-method basis.
  74. *
  75. * For example, if all text input fields should be wrapped in `<span />` tags, you can configure
  76. * the template string mappings per the following:
  77. *
  78. * {{{
  79. * $this->form->config(array('templates' => array(
  80. * 'text' => '<span><input type="text" name="{:name}"{:options} /></span>'
  81. * )));
  82. * }}}
  83. *
  84. * Alternatively, you can re-map one type as another. This is useful if, for example, you
  85. * include your own helper with custom form template strings which do not match the default
  86. * template string names.
  87. *
  88. * {{{
  89. * // Renders all password fields as text fields
  90. * $this->form->config(array('templates' => array('password' => 'text')));
  91. * }}}
  92. *
  93. * @var array
  94. * @see lithium\template\helper\Form::config()
  95. */
  96. protected $_templateMap = array(
  97. 'create' => 'form',
  98. 'end' => 'form-end'
  99. );
  100. /**
  101. * The data object or list of data objects to which the current form is bound. In order to
  102. * be a custom data object, a class must implement the following methods:
  103. *
  104. * - schema(): Returns an array defining the objects fields and their data types.
  105. * - data(): Returns an associative array of the data that this object represents.
  106. * - errors(): Returns an associatie array of validation errors for the current data set, where
  107. * the keys match keys from `schema()`, and the values are either strings (in cases
  108. * where a field only has one error) or an array (in case of multiple errors),
  109. *
  110. * For an example of how to implement these methods, see the `lithium\data\Entity` object.
  111. *
  112. * @see lithium\data\Entity
  113. * @see lithium\data\Collection
  114. * @see lithium\template\helper\Form::create()
  115. * @var mixed A single data object, a `Collection` of multiple data objects, or an array of data
  116. * objects/`Collection`s.
  117. */
  118. protected $_binding = null;
  119. /**
  120. * Array of options used to create the form to which `$_binding` is currently bound.
  121. * Overwritten when `end()` is called.
  122. *
  123. * @var array
  124. */
  125. protected $_bindingOptions = array();
  126. public function __construct(array $config = array()) {
  127. $self =& $this;
  128. $defaults = array(
  129. 'base' => array(),
  130. 'text' => array(),
  131. 'textarea' => array(),
  132. 'select' => array('multiple' => false),
  133. 'attributes' => array(
  134. 'id' => function($method, $name, $options) use (&$self) {
  135. if (in_array($method, array('create', 'end', 'label', 'error'))) {
  136. return;
  137. }
  138. if (!$name || ($method == 'hidden' && $name = '_method')) {
  139. return;
  140. }
  141. $id = Inflector::camelize($name);
  142. $model = ($binding = $self->binding()) ? $binding->model() : null;
  143. return $model ? basename(str_replace('\\', '/', $model)) . $id : $id;
  144. }
  145. )
  146. );
  147. parent::__construct(Set::merge($defaults, $config));
  148. }
  149. /**
  150. * Object initializer. Adds a content handler for the `wrap` key in the `field()` method, which
  151. * converts an array of properties to an attribute string.
  152. *
  153. * @return void
  154. */
  155. protected function _init() {
  156. parent::_init();
  157. $this->_context->handlers(array('wrap' => '_attributes'));
  158. }
  159. /**
  160. * Allows you to configure a default set of options which are included on a per-method basis,
  161. * and configure method template overrides.
  162. *
  163. * To force all `<label />` elements to have a default `class` attribute value of `"foo"`,
  164. * simply do the following:
  165. *
  166. * {{{
  167. * $this->form->config(array('label' => array('class' => 'foo')));
  168. * }}}
  169. *
  170. * Note that this can be overridden on a case-by-case basis, and when overridding, values are
  171. * not merged or combined. Therefore, if you wanted a particular `<label />` to have both `foo`
  172. * and `bar` as classes, you would have to specify `'class' => 'foo bar'`.
  173. *
  174. * You can also use this method to change the string template that a method uses to render its
  175. * content. For example, the default template for rendering a checkbox is
  176. * `'<input type="checkbox" name="{:name}"{:options} />'`. However, suppose you implemented your
  177. * own custom UI elements, and you wanted to change the markup used, you could do the following:
  178. *
  179. * {{{
  180. * $this->form->config(array('templates' => array(
  181. * 'checkbox' => '<div id="{:name}" class="ui-checkbox-element"{:options}></div>'
  182. * )));
  183. * }}}
  184. *
  185. * Now, for any calls to `$this->form->checkbox()`, your custom markup template will be applied.
  186. * This works for any `Form` method that renders HTML elements.
  187. *
  188. * @see lithium\template\helper\Form::$_templateMap
  189. * @param array $config An associative array where the keys are `Form` method names (or
  190. * `'templates'`, to include a template-overriding sub-array), and the
  191. * values are arrays of configuration options to be included in the `$options`
  192. * parameter of each method specified.
  193. * @return array Returns an array containing the currently set per-method configurations, and
  194. * an array of the currently set template overrides (in the `'templates'` array key).
  195. */
  196. public function config(array $config = array()) {
  197. if (!$config) {
  198. return array('templates' => $this->_templateMap) + array_intersect_key(
  199. $this->_config, array('base' => '', 'text' => '', 'textarea' => '')
  200. );
  201. }
  202. if (isset($config['templates'])) {
  203. $this->_templateMap = $config['templates'] + $this->_templateMap;
  204. unset($config['templates']);
  205. }
  206. return ($this->_config = Set::merge($this->_config, $config)) + array(
  207. 'templates' => $this->_templateMap
  208. );
  209. }
  210. /**
  211. * Creates an HTML form, and optionally binds it to a data object which contains information on
  212. * how to render form fields, any data to pre-populate the form with, and any validation errors.
  213. * Typically, a data object will be a `Record` object returned from a `Model`, but you can
  214. * define your own custom objects as well. For more information on custom data objects, see
  215. * `lithium\template\helper\Form::$_binding`.
  216. *
  217. * @see lithium\template\helper\Form::$_binding
  218. * @see lithium\data\Entity
  219. * @param object $binding The object to bind the form to. This is usually an instance of
  220. * `Record` or `Document`, or some other class that extends
  221. * `lithium\data\Entity`.
  222. * @param array $options Other parameters for creating the form. Available options are:
  223. * - `'url'` _mixed_: A string URL or URL array parameters defining where in the
  224. * application the form should be submitted to.
  225. * - `'action'` _string_: This is a shortcut to be used if you wish to only
  226. * specify the name of the action to submit to, and use the default URL
  227. * parameters (i.e. the current controller, etc.) for generating the remainder
  228. * of the URL. Ignored if the `'url'` key is set.
  229. * - `'type'` _string_: Currently the only valid option is `'file'`. Set this if
  230. * the form will be used for file uploads.
  231. * - `'method'` _string_: Represents the HTTP method with which the form will be
  232. * submitted (`'get'`, `'post'`, `'put'` or `'delete'`). If `'put'` or
  233. * `'delete'`, the request method is simulated using a hidden input field.
  234. * @return string Returns a `<form />` open tag with the `action` attribute defined by either
  235. * the `'action'` or `'url'` options (defaulting to the current page if none is
  236. * specified), the HTTP method is defined by the `'method'` option, and any HTML
  237. * attributes passed in `$options`.
  238. */
  239. public function create($binding = null, array $options = array()) {
  240. $defaults = array(
  241. 'url' => $this->_context->request()->params,
  242. 'type' => null,
  243. 'action' => null,
  244. 'method' => $binding ? ($binding->exists() ? 'put' : 'post') : 'post'
  245. );
  246. list(, $options, $tpl) = $this->_defaults(__FUNCTION__, null, $options);
  247. list($scope, $options) = $this->_options($defaults, $options);
  248. $_binding =& $this->_binding;
  249. $_options =& $this->_bindingOptions;
  250. $params = compact('scope', 'options', 'binding');
  251. $extra = array('method' => __METHOD__) + compact('tpl', 'defaults');
  252. $filter = function($self, $params, $chain) use ($extra, &$_binding, &$_options) {
  253. $scope = $params['scope'];
  254. $options = $params['options'];
  255. $_binding = $params['binding'];
  256. $append = null;
  257. $scope['method'] = strtolower($scope['method']);
  258. if ($scope['type'] == 'file') {
  259. if ($scope['method'] == 'get') {
  260. $scope['method'] = 'post';
  261. }
  262. $options['enctype'] = 'multipart/form-data';
  263. }
  264. if (!($scope['method'] == 'get' || $scope['method'] == 'post')) {
  265. $append = $self->hidden('_method', array('value' => strtoupper($scope['method'])));
  266. $scope['method'] = 'post';
  267. }
  268. $url = $scope['action'] ? array('action' => $scope['action']) : $scope['url'];
  269. $options['method'] = strtolower($scope['method']);
  270. $args = array($extra['method'], $extra['tpl'], compact('url', 'options', 'append'));
  271. $_options = $scope + $options;
  272. return $self->invokeMethod('_render', $args);
  273. };
  274. return $this->_filter(__METHOD__, $params, $filter);
  275. }
  276. /**
  277. * Echoes a closing `</form>` tag and unbinds the `Form` helper from any `Record` or `Document`
  278. * object used to generate the corresponding form.
  279. *
  280. * @return string Returns a closing `</form>` tag.
  281. */
  282. public function end() {
  283. list(, $options, $template) = $this->_defaults(__FUNCTION__, null, array());
  284. $params = compact('options', 'template');
  285. $_binding =& $this->_binding;
  286. $_context =& $this->_context;
  287. $_options =& $this->_bindingOptions;
  288. $filter = function($self, $params, $chain) use (&$_binding, &$_context, &$_options) {
  289. unset($_binding);
  290. $_options = array();
  291. return $_context->strings('form-end');
  292. };
  293. $result = $this->_filter(__METHOD__, $params, $filter);
  294. unset($this->_binding);
  295. $this->_binding = null;
  296. return $result;
  297. }
  298. /**
  299. * Returns the entity that the `Form` helper is currently bound to.
  300. *
  301. * @see lithium\template\helper\Form::$_binding
  302. * @return object Returns an object, usually an instance of `lithium\data\Entity`.
  303. */
  304. public function binding() {
  305. return $this->_binding;
  306. }
  307. /**
  308. * Implements alternative input types as method calls against `Form` helper. Enables the
  309. * generation of HTML5 input types and other custom input types:
  310. *
  311. * {{{ embed:lithium\tests\cases\template\helper\FormTest::testCustomInputTypes(1-2) }}}
  312. *
  313. * @param string $type The method called, which represents the `type` attribute of the
  314. * `<input />` tag.
  315. * @param array $params An array of method parameters passed to the method call. The first
  316. * element should be the name of the input field, and the second should be an array
  317. * of element attributes.
  318. * @return string Returns an `<input />` tag of the type specified in `$type`.
  319. */
  320. public function __call($type, array $params = array()) {
  321. $params += array(null, array());
  322. list($name, $options) = $params;
  323. list($name, $options, $template) = $this->_defaults($type, $name, $options);
  324. $template = $this->_context->strings($template) ? $template : 'element';
  325. return $this->_render($type, $template, compact('type', 'name', 'options', 'value'));
  326. }
  327. /**
  328. * Generates a form field with a label, input, and error message (if applicable), all contained
  329. * within a wrapping element.
  330. *
  331. * {{{
  332. * echo $this->form->field('name');
  333. * echo $this->form->field('present', array('type' => 'checkbox'));
  334. * echo $this->form->field(array('email' => 'Enter a valid email'));
  335. * echo $this->form->field(array('name','email','phone'),array('div' => false));
  336. * }}}
  337. * @param mixed $name The name of the field to render. If the form was bound to an object
  338. * passed in `create()`, `$name` should be the name of a field in that object.
  339. * Otherwise, can be any arbitrary field name, as it will appear in POST data.
  340. * Alternatively supply an array of fields that will use the same options
  341. * array($field1 => $label1, $field2, $field3 => $label3)
  342. * @param array $options Rendering options for the form field. The available options are as
  343. * follows:
  344. * - `'label'` _mixed_: A string or array defining the label text and / or
  345. * parameters. By default, the label text is a human-friendly version of `$name`.
  346. * However, you can specify the label manually as a string, or both the label
  347. * text and options as an array, i.e.:
  348. * `array('label text' => array('class' => 'foo', 'any' => 'other options'))`.
  349. * - `'type'` _string_: The type of form field to render. Available default options
  350. * are: `'text'`, `'textarea'`, `'select'`, `'checkbox'`, `'password'` or
  351. * `'hidden'`, as well as any arbitrary type (i.e. HTML5 form fields).
  352. * - `'template'` _string_: Defaults to `'template'`, but can be set to any named
  353. * template string, or an arbitrary HTML fragment. For example, to change the
  354. * default wrapper tag from `<div />` to `<li />`, you can pass the following:
  355. * `'<li{:wrap}>{:label}{:input}{:error}</li>'`.
  356. * - `'wrap'` _array_: An array of HTML attributes which will be embedded in the
  357. * wrapper tag.
  358. * - `list` _array_: If `'type'` is set to `'select'`, `'list'` is an array of
  359. * key/value pairs representing the `$list` parameter of the `select()` method.
  360. * @return string Returns a form input (the input type is based on the `'type'` option), with
  361. * label and error message, wrapped in a `<div />` element.
  362. */
  363. public function field($name, array $options = array()) {
  364. if (is_array($name)) {
  365. $return = '';
  366. foreach ($name as $field => $label) {
  367. if (is_numeric($field)) {
  368. $field = $label;
  369. unset($label);
  370. }
  371. $return .= $this->field($field, compact('label') + $options);
  372. }
  373. return $return;
  374. }
  375. $defaults = array(
  376. 'label' => null,
  377. 'type' => isset($options['list']) ? 'select' : 'text',
  378. 'template' => 'field',
  379. 'wrap' => array(),
  380. 'list' => null,
  381. );
  382. $type = isset($options['type']) ? $options['type'] : $defaults['type'];
  383. if ($this->_context->strings('field-' . $type)) {
  384. $defaults['template'] = 'field-' . $type;
  385. }
  386. list($options, $fieldOptions) = $this->_options($defaults, $options);
  387. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  388. if ($options['template'] != $defaults['template']) {
  389. $template = $options['template'];
  390. }
  391. $wrap = $options['wrap'];
  392. $type = $options['type'];
  393. $label = $input = null;
  394. if ($options['label'] === null || $options['label']) {
  395. $for = isset($options['id']) ? $options['id'] : '';
  396. $label = $options['label'] ?: $options['label'] = Inflector::humanize($name);
  397. $label = $this->label($for, $label);
  398. }
  399. switch (true) {
  400. case ($type == 'select'):
  401. $input = $this->select($name, $options['list'], $fieldOptions);
  402. break;
  403. default:
  404. $input = $this->{$type}($name, $fieldOptions);
  405. break;
  406. }
  407. $error = ($this->_binding) ? $this->error($name) : null;
  408. return $this->_render(__METHOD__, $template, compact('wrap', 'label', 'input', 'error'));
  409. }
  410. /**
  411. * Generates an HTML `<input type="submit" />` object.
  412. *
  413. * @param string $title The title of the submit button.
  414. * @param array $options Any options passed are converted to HTML attributes within the
  415. * `<input />` tag.
  416. * @return string Returns a submit `<input />` tag with the given title and HTML attributes.
  417. */
  418. public function submit($title = null, array $options = array()) {
  419. list($name, $options, $template) = $this->_defaults(__FUNCTION__, null, $options);
  420. return $this->_render(__METHOD__, $template, compact('title', 'options'));
  421. }
  422. /**
  423. * Generates an HTML `<textarea>...</textarea>` object.
  424. *
  425. * @param string $name The name of the field.
  426. * @param array $options The options to be used when generating the `<textarea />` tag pair,
  427. * which are as follows:
  428. * - `'value'` _string_: The content value of the field.
  429. * - Any other options specified are rendered as HTML attributes of the element.
  430. * @return string Returns a `<textarea>` tag with the given name and HTML attributes.
  431. */
  432. public function textarea($name, array $options = array()) {
  433. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  434. list($scope, $options) = $this->_options(array('value' => null), $options);
  435. $value = isset($scope['value']) ? $scope['value'] : '';
  436. return $this->_render(__METHOD__, $template, compact('name', 'options', 'value'));
  437. }
  438. /**
  439. * Generates an HTML `<input type="text" />` object.
  440. *
  441. * @param string $name The name of the field.
  442. * @param array $options All options passed are rendered as HTML attributes.
  443. * @return string Returns a `<input />` tag with the given name and HTML attributes.
  444. */
  445. public function text($name, array $options = array()) {
  446. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  447. return $this->_render(__METHOD__, $template, compact('name', 'options'));
  448. }
  449. /**
  450. * Generates a `<select />` list using the `$list` parameter for the `<option />` tags. The
  451. * default selection will be set to the value of `$options['value']`, if specified.
  452. *
  453. * For example: {{{
  454. * $this->form->select('colors', array(1 => 'red', 2 => 'green', 3 => 'blue'), array(
  455. * 'id' => 'Colors', 'value' => 2
  456. * ));
  457. * // Renders a '<select />' list with options 'red', 'green' and 'blue', with the 'green'
  458. * // option as the selection
  459. * }}}
  460. *
  461. * @param string $name The `name` attribute of the `<select />` element.
  462. * @param array $list An associative array of key/value pairs, which will be used to render the
  463. * list of options.
  464. * @param array $options Any HTML attributes that should be associated with the `<select />`
  465. * element. If the `'value'` key is set, this will be the value of the option
  466. * that is selected by default.
  467. * @return string Returns an HTML `<select />` element.
  468. */
  469. public function select($name, $list = array(), array $options = array()) {
  470. $defaults = array('empty' => false, 'value' => null);
  471. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  472. list($scope, $options) = $this->_options($defaults, $options);
  473. if ($scope['empty']) {
  474. $list = array('' => ($scope['empty'] === true) ? '' : $scope['empty']) + $list;
  475. }
  476. $startTemplate = ($scope['multiple']) ? 'select-multi-start' : 'select-start';
  477. $output = $this->_render(__METHOD__, $startTemplate, compact('name', 'options'));
  478. foreach ($list as $value => $title) {
  479. $selected = false;
  480. if (is_array($scope['value']) && in_array($value, $scope['value'])) {
  481. $selected = true;
  482. } elseif ($scope['value'] == $value) {
  483. $selected = true;
  484. }
  485. $options = $selected ? array('selected' => true) : array();
  486. $output .= $this->_render(__METHOD__, 'select-option', compact(
  487. 'value', 'title', 'options'
  488. ));
  489. }
  490. return $output . $this->_context->strings('select-end');
  491. }
  492. /**
  493. * Generates an HTML `<input type="checkbox" />` object.
  494. *
  495. * @param string $name The name of the field.
  496. * @param array $options Options to be used when generating the checkbox `<input />` element:
  497. * - `'checked'` _boolean_: Whether or not the field should be checked by default.
  498. * - `'value'` _mixed_: if specified, it will be used as the 'value' html
  499. * attribute and no hidden input field will be added
  500. * - Any other options specified are rendered as HTML attributes of the element.
  501. * @return string Returns a `<input />` tag with the given name and HTML attributes.
  502. */
  503. public function checkbox($name, array $options = array()) {
  504. $defaults = array('value' => '1', 'hidden' => true);
  505. $options += $defaults;
  506. $default = $options['value'];
  507. $out = '';
  508. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  509. list($scope, $options) = $this->_options($defaults, $options);
  510. if (!isset($options['checked'])) {
  511. if ($this->_binding && $bound = $this->_binding->data($name)) {
  512. $options['checked'] = !($bound === $default);
  513. } else {
  514. $options['checked'] = ($scope['value'] != $default);
  515. }
  516. }
  517. if ($scope['hidden']) {
  518. $out = $this->hidden($name, array('value' => ''));
  519. }
  520. $options['value'] = $scope['value'];
  521. return $out . $this->_render(__METHOD__, $template, compact('name', 'options'));
  522. }
  523. /**
  524. * Generates an HTML `<input type="password" />` object.
  525. *
  526. * @param string $name The name of the field.
  527. * @param array $options An array of HTML attributes with which the field should be rendered.
  528. * @return string Returns a `<input />` tag with the given name and HTML attributes.
  529. */
  530. public function password($name, array $options = array()) {
  531. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  532. return $this->_render(__METHOD__, $template, compact('name', 'options'));
  533. }
  534. /**
  535. * Generates an HTML `<input type="hidden" />` object.
  536. *
  537. * @param string $name The name of the field.
  538. * @param array $options An array of HTML attributes with which the field should be rendered.
  539. * @return string Returns a `<input />` tag with the given name and HTML attributes.
  540. */
  541. public function hidden($name, array $options = array()) {
  542. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  543. return $this->_render(__METHOD__, $template, compact('name', 'options'));
  544. }
  545. /**
  546. * Generates an HTML `<label></label>` object.
  547. *
  548. * @param string $name The name of the field that the label is for.
  549. * @param string $title The content inside the `<label></label>` object.
  550. * @param array $options Besides HTML attributes, this parameter allows one additional flag:
  551. * - `'escape'` _boolean_: Defaults to `true`. Indicates whether the title of the
  552. * label should be escaped. If `false`, it will be treated as raw HTML.
  553. * @return string Returns a `<label>` tag for the name and with HTML attributes.
  554. */
  555. public function label($name, $title = null, array $options = array()) {
  556. $defaults = array('escape' => true);
  557. if (is_array($title)) {
  558. list($title, $options) = each($title);
  559. }
  560. $title = $title ?: Inflector::humanize($name);
  561. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  562. list($scope, $options) = $this->_options($defaults, $options);
  563. return $this->_render(__METHOD__, $template, compact('name', 'title', 'options'), $scope);
  564. }
  565. /**
  566. * Generates an error message for a field which is part of an object bound to a form in
  567. * `create()`.
  568. *
  569. * @param string $name The name of the field for which to render an error.
  570. * @param mixed $key If more than one error is present for `$name`, a key may be specified.
  571. * If `$key` is not set in the array of errors, or if `$key` is `true`, the first
  572. * available error is used.
  573. * @param array $options Any rendering options or HTML attributes to be used when rendering
  574. * the error.
  575. * @return string Returns a rendered error message based on the `'error'` string template.
  576. */
  577. public function error($name, $key = null, array $options = array()) {
  578. $defaults = array('class' => 'error');
  579. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  580. $options += $defaults;
  581. $result = '';
  582. if (isset($options['value'])) {
  583. unset($options['value']);
  584. }
  585. if (!$this->_binding || !$content = $this->_binding->errors($name)) {
  586. return null;
  587. }
  588. if (is_array($content)) {
  589. $errors = $content;
  590. if ($key !== null) {
  591. $content = !isset($errors[$key]) || $key === true ? reset($errors) : $errors[$key];
  592. } else {
  593. foreach ($errors as $content) {
  594. $result .= $this->_render(__METHOD__, $template, compact('content', 'options'));
  595. }
  596. return $result;
  597. }
  598. }
  599. return $this->_render(__METHOD__, $template, compact('content', 'options'));
  600. }
  601. /**
  602. * Builds the defaults array for a method by name, according to the config.
  603. *
  604. * @param string $method The name of the method to create defaults for.
  605. * @param string $name The `$name` supplied to the original method.
  606. * @param string $options `$options` from the original method.
  607. * @return array Defaults array contents.
  608. */
  609. protected function _defaults($method, $name, $options) {
  610. $methodConfig = isset($this->_config[$method]) ? $this->_config[$method] : array();
  611. $options += $methodConfig + $this->_config['base'];
  612. foreach ($this->_config['attributes'] as $key => $generator) {
  613. if (!isset($options[$key]) && $generator) {
  614. if (($attr = $generator($method, $name, $options)) !== null) {
  615. $options[$key] = $attr;
  616. }
  617. }
  618. }
  619. $hasValue = (
  620. (!isset($options['value']) || $options['value'] === null) &&
  621. $name && $this->_binding && $value = $this->_binding->data($name)
  622. );
  623. if ($hasValue) {
  624. $options['value'] = $value;
  625. }
  626. if (isset($options['default']) && empty($options['value'])) {
  627. $options['value'] = $options['default'];
  628. }
  629. unset($options['default']);
  630. $tplKey = isset($options['template']) ? $options['template'] : $method;
  631. $template = isset($this->_templateMap[$tplKey]) ? $this->_templateMap[$tplKey] : $tplKey;
  632. return array($name, $options, $template);
  633. }
  634. }
  635. ?>