PageRenderTime 48ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/template/helper/Form.php

https://github.com/ifunk/lithium
PHP | 771 lines | 683 code | 10 blank | 78 comment | 13 complexity | 018bc44e8f343d238b722052ccefc385 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. * Lithium: the most rad php framework
  4. *
  5. * @copyright Copyright 2011, 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. /**
  12. * A helper class to facilitate generating, processing and securing HTML forms. By default, `Form`
  13. * will simply generate HTML forms and widgets, but by creating a form with a _binding object_,
  14. * the helper can pre-fill form input values, render error messages, and introspect column types.
  15. *
  16. * For example, assuming you have created a `Posts` model in your application:
  17. * {{{// In controller code:
  18. * use app\models\Posts;
  19. * $post = Posts::find(1);
  20. * return compact('post');
  21. *
  22. * // In view code:
  23. * <?=$this->form->create($post); // Echoes a <form> tag and binds the helper to $post ?>
  24. * <?=$this->form->text('title'); // Echoes an <input /> element, pre-filled with $post's title ?>
  25. * <?=$this->form->submit('Update'); // Echoes a submit button with the title 'Update' ?>
  26. * <?=$this->form->end(); // Echoes a </form> tag & unbinds the form ?>
  27. * }}}
  28. */
  29. class Form extends \lithium\template\Helper {
  30. /**
  31. * String templates used by this helper.
  32. *
  33. * @var array
  34. */
  35. protected $_strings = array(
  36. 'button' => '<button{:options}>{:name}</button>',
  37. 'checkbox' => '<input type="checkbox" name="{:name}"{:options} />',
  38. 'checkbox-multi' => '<input type="checkbox" name="{:name}[]"{:options} />',
  39. 'checkbox-multi-group' => '{:raw}',
  40. 'error' => '<div{:options}>{:content}</div>',
  41. 'errors' => '{:raw}',
  42. 'input' => '<input type="{:type}" name="{:name}"{:options} />',
  43. 'file' => '<input type="file" name="{:name}"{:options} />',
  44. 'form' => '<form action="{:url}"{:options}>{:append}',
  45. 'form-end' => '</form>',
  46. 'hidden' => '<input type="hidden" name="{:name}"{:options} />',
  47. 'field' => '<div{:wrap}>{:label}{:input}{:error}</div>',
  48. 'field-checkbox' => '<div{:wrap}>{:input}{:label}{:error}</div>',
  49. 'field-radio' => '<div{:wrap}>{:input}{:label}{:error}</div>',
  50. 'label' => '<label for="{:name}"{:options}>{:title}</label>',
  51. 'legend' => '<legend>{:content}</legend>',
  52. 'option-group' => '<optgroup label="{:label}"{:options}>{:raw}</optgroup>',
  53. 'password' => '<input type="password" name="{:name}"{:options} />',
  54. 'radio' => '<input type="radio" name="{:name}" {:options} />',
  55. 'select' => '<select name="{:name}"{:options}>{:raw}</select>',
  56. 'select-empty' => '<option value=""{:options}>&nbsp;</option>',
  57. 'select-multi' => '<select name="{:name}[]"{:options}>{:raw}</select>',
  58. 'select-option' => '<option value="{:value}"{:options}>{:title}</option>',
  59. 'submit' => '<input type="submit" value="{:title}"{:options} />',
  60. 'submit-image' => '<input type="image" src="{:url}"{:options} />',
  61. 'text' => '<input type="text" name="{:name}"{:options} />',
  62. 'textarea' => '<textarea name="{:name}"{:options}>{:value}</textarea>',
  63. 'fieldset' => '<fieldset{:options}><legend>{:content}</legend>{:raw}</fieldset>',
  64. );
  65. /**
  66. * Maps method names to template string names, allowing the default template strings to be set
  67. * permanently on a per-method basis.
  68. *
  69. * For example, if all text input fields should be wrapped in `<span />` tags, you can configure
  70. * the template string mappings per the following:
  71. *
  72. * {{{
  73. * $this->form->config(array('templates' => array(
  74. * 'text' => '<span><input type="text" name="{:name}"{:options} /></span>'
  75. * )));
  76. * }}}
  77. *
  78. * Alternatively, you can re-map one type as another. This is useful if, for example, you
  79. * include your own helper with custom form template strings which do not match the default
  80. * template string names.
  81. *
  82. * {{{
  83. * // Renders all password fields as text fields
  84. * $this->form->config(array('templates' => array('password' => 'text')));
  85. * }}}
  86. *
  87. * @var array
  88. * @see lithium\template\helper\Form::config()
  89. */
  90. protected $_templateMap = array(
  91. 'create' => 'form',
  92. 'end' => 'form-end'
  93. );
  94. /**
  95. * The data object or list of data objects to which the current form is bound. In order to
  96. * be a custom data object, a class must implement the following methods:
  97. *
  98. * - schema(): Returns an array defining the objects fields and their data types.
  99. * - data(): Returns an associative array of the data that this object represents.
  100. * - errors(): Returns an associatie array of validation errors for the current data set, where
  101. * the keys match keys from `schema()`, and the values are either strings (in cases
  102. * where a field only has one error) or an array (in case of multiple errors),
  103. *
  104. * For an example of how to implement these methods, see the `lithium\data\Entity` object.
  105. *
  106. * @see lithium\data\Entity
  107. * @see lithium\data\Collection
  108. * @see lithium\template\helper\Form::create()
  109. * @var mixed A single data object, a `Collection` of multiple data objects, or an array of data
  110. * objects/`Collection`s.
  111. */
  112. protected $_binding = null;
  113. /**
  114. * Array of options used to create the form to which `$_binding` is currently bound.
  115. * Overwritten when `end()` is called.
  116. *
  117. * @var array
  118. */
  119. protected $_bindingOptions = array();
  120. public function __construct(array $config = array()) {
  121. $self =& $this;
  122. $defaults = array(
  123. 'base' => array(),
  124. 'text' => array(),
  125. 'textarea' => array(),
  126. 'select' => array('multiple' => false),
  127. 'attributes' => array(
  128. 'id' => function($method, $name, $options) use (&$self) {
  129. if (in_array($method, array('create', 'end', 'label', 'error'))) {
  130. return;
  131. }
  132. if (!$name || ($method == 'hidden' && $name == '_method')) {
  133. return;
  134. }
  135. $id = Inflector::camelize(Inflector::slug($name));
  136. $model = ($binding = $self->binding()) ? $binding->model() : null;
  137. return $model ? basename(str_replace('\\', '/', $model)) . $id : $id;
  138. }
  139. )
  140. );
  141. parent::__construct(Set::merge($defaults, $config));
  142. }
  143. /**
  144. * Object initializer. Adds a content handler for the `wrap` key in the `field()` method, which
  145. * converts an array of properties to an attribute string.
  146. *
  147. * @return void
  148. */
  149. protected function _init() {
  150. parent::_init();
  151. if ($this->_context) {
  152. $this->_context->handlers(array('wrap' => '_attributes'));
  153. }
  154. }
  155. /**
  156. * Allows you to configure a default set of options which are included on a per-method basis,
  157. * and configure method template overrides.
  158. *
  159. * To force all `<label />` elements to have a default `class` attribute value of `"foo"`,
  160. * simply do the following:
  161. *
  162. * {{{
  163. * $this->form->config(array('label' => array('class' => 'foo')));
  164. * }}}
  165. *
  166. * Note that this can be overridden on a case-by-case basis, and when overridding, values are
  167. * not merged or combined. Therefore, if you wanted a particular `<label />` to have both `foo`
  168. * and `bar` as classes, you would have to specify `'class' => 'foo bar'`.
  169. *
  170. * You can also use this method to change the string template that a method uses to render its
  171. * content. For example, the default template for rendering a checkbox is
  172. * `'<input type="checkbox" name="{:name}"{:options} />'`. However, suppose you implemented your
  173. * own custom UI elements, and you wanted to change the markup used, you could do the following:
  174. *
  175. * {{{
  176. * $this->form->config(array('templates' => array(
  177. * 'checkbox' => '<div id="{:name}" class="ui-checkbox-element"{:options}></div>'
  178. * )));
  179. * }}}
  180. *
  181. * Now, for any calls to `$this->form->checkbox()`, your custom markup template will be applied.
  182. * This works for any `Form` method that renders HTML elements.
  183. *
  184. * @see lithium\template\helper\Form::$_templateMap
  185. * @param array $config An associative array where the keys are `Form` method names (or
  186. * `'templates'`, to include a template-overriding sub-array), and the
  187. * values are arrays of configuration options to be included in the `$options`
  188. * parameter of each method specified.
  189. * @return array Returns an array containing the currently set per-method configurations, and
  190. * an array of the currently set template overrides (in the `'templates'` array key).
  191. */
  192. public function config(array $config = array()) {
  193. if (!$config) {
  194. $keys = array('base' => '', 'text' => '', 'textarea' => '', 'attributes' => '');
  195. return array('templates' => $this->_templateMap) + array_intersect_key(
  196. $this->_config, $keys
  197. );
  198. }
  199. if (isset($config['templates'])) {
  200. $this->_templateMap = $config['templates'] + $this->_templateMap;
  201. unset($config['templates']);
  202. }
  203. return ($this->_config = Set::merge($this->_config, $config)) + array(
  204. 'templates' => $this->_templateMap
  205. );
  206. }
  207. /**
  208. * Creates an HTML form, and optionally binds it to a data object which contains information on
  209. * how to render form fields, any data to pre-populate the form with, and any validation errors.
  210. * Typically, a data object will be a `Record` object returned from a `Model`, but you can
  211. * define your own custom objects as well. For more information on custom data objects, see
  212. * `lithium\template\helper\Form::$_binding`.
  213. *
  214. * @see lithium\template\helper\Form::$_binding
  215. * @see lithium\data\Entity
  216. * @param object $binding The object to bind the form to. This is usually an instance of
  217. * `Record` or `Document`, or some other class that extends
  218. * `lithium\data\Entity`.
  219. * @param array $options Other parameters for creating the form. Available options are:
  220. * - `'url'` _mixed_: A string URL or URL array parameters defining where in the
  221. * application the form should be submitted to.
  222. * - `'action'` _string_: This is a shortcut to be used if you wish to only
  223. * specify the name of the action to submit to, and use the default URL
  224. * parameters (i.e. the current controller, etc.) for generating the remainder
  225. * of the URL. Ignored if the `'url'` key is set.
  226. * - `'type'` _string_: Currently the only valid option is `'file'`. Set this if
  227. * the form will be used for file uploads.
  228. * - `'method'` _string_: Represents the HTTP method with which the form will be
  229. * submitted (`'get'`, `'post'`, `'put'` or `'delete'`). If `'put'` or
  230. * `'delete'`, the request method is simulated using a hidden input field.
  231. * @return string Returns a `<form />` open tag with the `action` attribute defined by either
  232. * the `'action'` or `'url'` options (defaulting to the current page if none is
  233. * specified), the HTTP method is defined by the `'method'` option, and any HTML
  234. * attributes passed in `$options`.
  235. * @filter
  236. */
  237. public function create($binding = null, array $options = array()) {
  238. $request = $this->_context ? $this->_context->request() : null;
  239. $defaults = array(
  240. 'url' => $request ? $request->params : array(),
  241. 'type' => null,
  242. 'action' => null,
  243. 'method' => $binding ? ($binding->exists() ? 'put' : 'post') : 'post'
  244. );
  245. list(, $options, $tpl) = $this->_defaults(__FUNCTION__, null, $options);
  246. list($scope, $options) = $this->_options($defaults, $options);
  247. $_binding =& $this->_binding;
  248. $_options =& $this->_bindingOptions;
  249. $params = compact('scope', 'options', 'binding');
  250. $extra = array('method' => __METHOD__) + compact('tpl', 'defaults');
  251. $filter = function($self, $params) use ($extra, &$_binding, &$_options) {
  252. $scope = $params['scope'];
  253. $options = $params['options'];
  254. $_binding = $params['binding'];
  255. $append = null;
  256. $scope['method'] = strtolower($scope['method']);
  257. if ($scope['type'] == 'file') {
  258. if ($scope['method'] == 'get') {
  259. $scope['method'] = 'post';
  260. }
  261. $options['enctype'] = 'multipart/form-data';
  262. }
  263. if (!($scope['method'] == 'get' || $scope['method'] == 'post')) {
  264. $append = $self->hidden('_method', array('value' => strtoupper($scope['method'])));
  265. $scope['method'] = 'post';
  266. }
  267. $url = $scope['action'] ? array('action' => $scope['action']) : $scope['url'];
  268. $options['method'] = strtolower($scope['method']);
  269. $args = array($extra['method'], $extra['tpl'], compact('url', 'options', 'append'));
  270. $_options = $scope + $options;
  271. return $self->invokeMethod('_render', $args);
  272. };
  273. return $this->_filter(__METHOD__, $params, $filter);
  274. }
  275. /**
  276. * Echoes a closing `</form>` tag and unbinds the `Form` helper from any `Record` or `Document`
  277. * object used to generate the corresponding form.
  278. *
  279. * @return string Returns a closing `</form>` tag.
  280. * @filter
  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) 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 : 'input';
  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 $this->_fields($name, $options);
  366. }
  367. $defaults = array(
  368. 'label' => null,
  369. 'type' => isset($options['list']) ? 'select' : 'text',
  370. 'template' => 'field',
  371. 'wrap' => array(),
  372. 'list' => null
  373. );
  374. $type = isset($options['type']) ? $options['type'] : $defaults['type'];
  375. if ($this->_context->strings('field-' . $type)) {
  376. $options['template'] = 'field-' . $type;
  377. }
  378. list(, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  379. list($options, $fieldOptions) = $this->_options($defaults, $options);
  380. if ($options['template'] != $defaults['template']) {
  381. $template = $options['template'];
  382. }
  383. $wrap = $options['wrap'];
  384. $type = $options['type'];
  385. $label = $input = null;
  386. if (($options['label'] === null || $options['label']) && $options['type'] != 'hidden') {
  387. if (!$options['label']) {
  388. $options['label'] = Inflector::humanize(preg_replace('/[\[\]\.]/', '_', $name));
  389. }
  390. $label = $this->label(isset($options['id']) ? $options['id'] : '', $options['label']);
  391. }
  392. switch (true) {
  393. case ($type == 'select'):
  394. $input = $this->select($name, $options['list'], $fieldOptions);
  395. break;
  396. default:
  397. $input = $this->{$type}($name, $fieldOptions);
  398. break;
  399. }
  400. $error = ($this->_binding) ? $this->error($name) : null;
  401. return $this->_render(__METHOD__, $template, compact('wrap', 'label', 'input', 'error'));
  402. }
  403. /**
  404. * Helper method used by `Form::field()` for iterating over an array of multiple fields.
  405. *
  406. * @see lithium\template\helper\Form::field()
  407. * @param array $fields An array of fields to render.
  408. * @param array $options The array of options to apply to all fields in the `$fields` array. See
  409. * the `$options` parameter of the `field` method for more information.
  410. * @return string Returns the fields rendered by `field()`, each separated by a newline.
  411. */
  412. protected function _fields(array $fields, array $options = array()) {
  413. $result = array();
  414. foreach ($fields as $field => $label) {
  415. if (is_numeric($field)) {
  416. $field = $label;
  417. unset($label);
  418. }
  419. $result[] = $this->field($field, compact('label') + $options);
  420. }
  421. return join("\n", $result);
  422. }
  423. /**
  424. * Generates an HTML `<input type="submit" />` object.
  425. *
  426. * @param string $title The title of the submit button.
  427. * @param array $options Any options passed are converted to HTML attributes within the
  428. * `<input />` tag.
  429. * @return string Returns a submit `<input />` tag with the given title and HTML attributes.
  430. */
  431. public function submit($title = null, array $options = array()) {
  432. list($name, $options, $template) = $this->_defaults(__FUNCTION__, null, $options);
  433. return $this->_render(__METHOD__, $template, compact('title', 'options'));
  434. }
  435. /**
  436. * Generates an HTML `<textarea>...</textarea>` object.
  437. *
  438. * @param string $name The name of the field.
  439. * @param array $options The options to be used when generating the `<textarea />` tag pair,
  440. * which are as follows:
  441. * - `'value'` _string_: The content value of the field.
  442. * - Any other options specified are rendered as HTML attributes of the element.
  443. * @return string Returns a `<textarea>` tag with the given name and HTML attributes.
  444. */
  445. public function textarea($name, array $options = array()) {
  446. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  447. list($scope, $options) = $this->_options(array('value' => null), $options);
  448. $value = isset($scope['value']) ? $scope['value'] : '';
  449. return $this->_render(__METHOD__, $template, compact('name', 'options', 'value'));
  450. }
  451. /**
  452. * Generates an HTML `<input type="text" />` object.
  453. *
  454. * @param string $name The name of the field.
  455. * @param array $options All options passed are rendered as HTML attributes.
  456. * @return string Returns a `<input />` tag with the given name and HTML attributes.
  457. */
  458. public function text($name, array $options = array()) {
  459. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  460. return $this->_render(__METHOD__, $template, compact('name', 'options'));
  461. }
  462. /**
  463. * Generates a `<select />` list using the `$list` parameter for the `<option />` tags. The
  464. * default selection will be set to the value of `$options['value']`, if specified.
  465. *
  466. * For example: {{{
  467. * $this->form->select('colors', array(1 => 'red', 2 => 'green', 3 => 'blue'), array(
  468. * 'id' => 'Colors', 'value' => 2
  469. * ));
  470. * // Renders a '<select />' list with options 'red', 'green' and 'blue', with the 'green'
  471. * // option as the selection
  472. * }}}
  473. *
  474. * @param string $name The `name` attribute of the `<select />` element.
  475. * @param array $list An associative array of key/value pairs, which will be used to render the
  476. * list of options.
  477. * @param array $options Any HTML attributes that should be associated with the `<select />`
  478. * element. If the `'value'` key is set, this will be the value of the option
  479. * that is selected by default.
  480. * @return string Returns an HTML `<select />` element.
  481. */
  482. public function select($name, $list = array(), array $options = array()) {
  483. $defaults = array('empty' => false, 'value' => null);
  484. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  485. list($scope, $options) = $this->_options($defaults, $options);
  486. if ($scope['empty']) {
  487. $list = array('' => ($scope['empty'] === true) ? '' : $scope['empty']) + $list;
  488. }
  489. if ($template == __FUNCTION__ && $scope['multiple']) {
  490. $template = 'select-multi';
  491. }
  492. $raw = $this->_selectOptions($list, $scope);
  493. return $this->_render(__METHOD__, $template, compact('name', 'options', 'raw'));
  494. }
  495. /**
  496. * Generator method used by `select()` to produce `<option />` and `<optgroup />` elements.
  497. * Generally, this method should not need to be called directly, but through `select()`.
  498. *
  499. * @param array $list Either a flat key/value array of select menu options, or an array which
  500. * contains key/value elements and/or elements where the keys are `<optgroup />`
  501. * titles and the values are sub-arrays of key/value pairs representing nested
  502. * `<option />` elements.
  503. * @param array $scope An array of options passed to the parent scope, including the currently
  504. * selected value of the associated form element.
  505. * @return string Returns a string of `<option />` and (optionally) `<optgroup />` tags to be
  506. * embedded in a select element.
  507. */
  508. protected function _selectOptions(array $list, array $scope) {
  509. $result = "";
  510. foreach ($list as $value => $title) {
  511. if (is_array($title)) {
  512. $label = $value;
  513. $options = array();
  514. $raw = $this->_selectOptions($title, $scope);
  515. $params = compact('label', 'options', 'raw');
  516. $result .= $this->_render('select', 'option-group', $params);
  517. continue;
  518. }
  519. $selected = (
  520. (is_array($scope['value']) && in_array($value, $scope['value'])) ||
  521. ($scope['value'] == $value)
  522. );
  523. $options = $selected ? array('selected' => true) : array();
  524. $params = compact('value', 'title', 'options');
  525. $result .= $this->_render('select', 'select-option', $params);
  526. }
  527. return $result;
  528. }
  529. /**
  530. * Generates an HTML `<input type="checkbox" />` object.
  531. *
  532. * @param string $name The name of the field.
  533. * @param array $options Options to be used when generating the checkbox `<input />` element:
  534. * - `'checked'` _boolean_: Whether or not the field should be checked by default.
  535. * - `'value'` _mixed_: if specified, it will be used as the 'value' html
  536. * attribute and no hidden input field will be added
  537. * - Any other options specified are rendered as HTML attributes of the element.
  538. * @return string Returns a `<input />` tag with the given name and HTML attributes.
  539. */
  540. public function checkbox($name, array $options = array()) {
  541. $defaults = array('value' => '1', 'hidden' => true);
  542. $options += $defaults;
  543. $default = $options['value'];
  544. $out = '';
  545. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  546. list($scope, $options) = $this->_options($defaults, $options);
  547. if (!isset($options['checked'])) {
  548. if ($this->_binding && $bound = $this->_binding->data($name)) {
  549. $options['checked'] = !($bound === $default);
  550. } else {
  551. $options['checked'] = ($scope['value'] != $default);
  552. }
  553. }
  554. if ($scope['hidden']) {
  555. $out = $this->hidden($name, array('value' => '', 'id' => false));
  556. }
  557. $options['value'] = $scope['value'];
  558. return $out . $this->_render(__METHOD__, $template, compact('name', 'options'));
  559. }
  560. /**
  561. * Generates an HTML `<input type="password" />` object.
  562. *
  563. * @param string $name The name of the field.
  564. * @param array $options An array of HTML attributes with which the field should be rendered.
  565. * @return string Returns a `<input />` tag with the given name and HTML attributes.
  566. */
  567. public function password($name, array $options = array()) {
  568. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  569. unset($options['value']);
  570. return $this->_render(__METHOD__, $template, compact('name', 'options'));
  571. }
  572. /**
  573. * Generates an HTML `<input type="hidden" />` object.
  574. *
  575. * @param string $name The name of the field.
  576. * @param array $options An array of HTML attributes with which the field should be rendered.
  577. * @return string Returns a `<input />` tag with the given name and HTML attributes.
  578. */
  579. public function hidden($name, array $options = array()) {
  580. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  581. return $this->_render(__METHOD__, $template, compact('name', 'options'));
  582. }
  583. /**
  584. * Generates an HTML `<label></label>` object.
  585. *
  586. * @param string $name The DOM ID of the field that the label is for.
  587. * @param string $title The content inside the `<label></label>` object.
  588. * @param array $options Besides HTML attributes, this parameter allows one additional flag:
  589. * - `'escape'` _boolean_: Defaults to `true`. Indicates whether the title of the
  590. * label should be escaped. If `false`, it will be treated as raw HTML.
  591. * @return string Returns a `<label>` tag for the name and with HTML attributes.
  592. */
  593. public function label($name, $title = null, array $options = array()) {
  594. $defaults = array('escape' => true);
  595. if (is_array($title)) {
  596. list($title, $options) = each($title);
  597. }
  598. $title = $title ?: Inflector::humanize($name);
  599. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  600. list($scope, $options) = $this->_options($defaults, $options);
  601. return $this->_render(__METHOD__, $template, compact('name', 'title', 'options'), $scope);
  602. }
  603. /**
  604. * Generates an error message for a field which is part of an object bound to a form in
  605. * `create()`.
  606. *
  607. * @param string $name The name of the field for which to render an error.
  608. * @param mixed $key If more than one error is present for `$name`, a key may be specified.
  609. * If `$key` is not set in the array of errors, or if `$key` is `true`, the first
  610. * available error is used.
  611. * @param array $options Any rendering options or HTML attributes to be used when rendering
  612. * the error.
  613. * @return string Returns a rendered error message based on the `'error'` string template.
  614. */
  615. public function error($name, $key = null, array $options = array()) {
  616. $defaults = array('class' => 'error');
  617. list(, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  618. $options += $defaults;
  619. $_binding =& $this->_binding;
  620. $params = compact('name', 'key', 'options', 'template');
  621. return $this->_filter(__METHOD__, $params, function($self, $params) use (&$_binding) {
  622. $options = $params['options'];
  623. $template = $params['template'];
  624. if (isset($options['value'])) {
  625. unset($options['value']);
  626. }
  627. if (!$_binding || !$content = $_binding->errors($params['name'])) {
  628. return null;
  629. }
  630. $result = '';
  631. if (!is_array($content)) {
  632. $args = array(__METHOD__, $template, compact('content', 'options'));
  633. return $self->invokeMethod('_render', $args);
  634. }
  635. $errors = $content;
  636. if ($params['key'] === null) {
  637. foreach ($errors as $content) {
  638. $args = array(__METHOD__, $template, compact('content', 'options'));
  639. $result .= $self->invokeMethod('_render', $args);
  640. }
  641. return $result;
  642. }
  643. $key = $params['key'];
  644. $content = !isset($errors[$key]) || $key === true ? reset($errors) : $errors[$key];
  645. $args = array(__METHOD__, $template, compact('content', 'options'));
  646. return $self->invokeMethod('_render', $args);
  647. });
  648. }
  649. /**
  650. * Builds the defaults array for a method by name, according to the config.
  651. *
  652. * @param string $method The name of the method to create defaults for.
  653. * @param string $name The `$name` supplied to the original method.
  654. * @param string $options `$options` from the original method.
  655. * @return array Defaults array contents.
  656. */
  657. protected function _defaults($method, $name, $options) {
  658. $methodConfig = isset($this->_config[$method]) ? $this->_config[$method] : array();
  659. $options += $methodConfig + $this->_config['base'];
  660. $options = $this->_generators($method, $name, $options);
  661. $hasValue = (
  662. (!isset($options['value']) || $options['value'] === null) &&
  663. $name && $this->_binding && $value = $this->_binding->data($name)
  664. );
  665. if ($hasValue) {
  666. $options['value'] = $value;
  667. }
  668. if (isset($options['default']) && empty($options['value'])) {
  669. $options['value'] = $options['default'];
  670. }
  671. unset($options['default']);
  672. if (strpos($name, '.')) {
  673. $name = explode('.', $name);
  674. $first = array_shift($name);
  675. $name = $first . '[' . join('][', $name) . ']';
  676. }
  677. $tplKey = isset($options['template']) ? $options['template'] : $method;
  678. $template = isset($this->_templateMap[$tplKey]) ? $this->_templateMap[$tplKey] : $tplKey;
  679. return array($name, $options, $template);
  680. }
  681. /**
  682. * Iterates over the configured attribute generators, and modifies the settings for a tag.
  683. *
  684. * @param string $method The name of the helper method which was called, i.e. `'text'`,
  685. * `'select'`, etc.
  686. * @param string $name The name of the field whose attributes are being generated. Some helper
  687. * methods, such as `create()` and `end()`, are not field-based, and therefore
  688. * will have no name.
  689. * @param array $options The options and HTML attributes that will be used to generate the
  690. * helper output.
  691. * @return array Returns the value of the `$options` array, modified by the attribute generators
  692. * added in the `'attributes'` key of the helper's configuration. Note that if a
  693. * generator is present for a field whose value is `false`, that field will be removed
  694. * from the array.
  695. */
  696. protected function _generators($method, $name, $options) {
  697. foreach ($this->_config['attributes'] as $key => $generator) {
  698. if ($generator && !isset($options[$key])) {
  699. if (($attr = $generator($method, $name, $options)) !== null) {
  700. $options[$key] = $attr;
  701. }
  702. continue;
  703. }
  704. if ($generator && $options[$key] === false) {
  705. unset($options[$key]);
  706. }
  707. }
  708. return $options;
  709. }
  710. }
  711. ?>