PageRenderTime 69ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/template/helper/Form.php

https://github.com/Daikoun/lithium
PHP | 804 lines | 716 code | 10 blank | 78 comment | 15 complexity | 0a9beb3f075fa01e5a0c6b428551189f MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. * Lithium: the most rad php framework
  4. *
  5. * @copyright Copyright 2012, 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="{:id}"{: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 associate 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. 'name' => function($method, $name, $options) {
  140. if (!strpos($name, '.')) {
  141. return $name;
  142. }
  143. $name = explode('.', $name);
  144. $first = array_shift($name);
  145. return $first . '[' . join('][', $name) . ']';
  146. }
  147. )
  148. );
  149. parent::__construct(Set::merge($defaults, $config));
  150. }
  151. /**
  152. * Object initializer. Adds a content handler for the `wrap` key in the `field()` method, which
  153. * converts an array of properties to an attribute string.
  154. *
  155. * @return void
  156. */
  157. protected function _init() {
  158. parent::_init();
  159. if ($this->_context) {
  160. $this->_context->handlers(array('wrap' => '_attributes'));
  161. }
  162. }
  163. /**
  164. * Allows you to configure a default set of options which are included on a per-method basis,
  165. * and configure method template overrides.
  166. *
  167. * To force all `<label />` elements to have a default `class` attribute value of `"foo"`,
  168. * simply do the following:
  169. *
  170. * {{{
  171. * $this->form->config(array('label' => array('class' => 'foo')));
  172. * }}}
  173. *
  174. * Note that this can be overridden on a case-by-case basis, and when overriding, values are
  175. * not merged or combined. Therefore, if you wanted a particular `<label />` to have both `foo`
  176. * and `bar` as classes, you would have to specify `'class' => 'foo bar'`.
  177. *
  178. * You can also use this method to change the string template that a method uses to render its
  179. * content. For example, the default template for rendering a checkbox is
  180. * `'<input type="checkbox" name="{:name}"{:options} />'`. However, suppose you implemented your
  181. * own custom UI elements, and you wanted to change the markup used, you could do the following:
  182. *
  183. * {{{
  184. * $this->form->config(array('templates' => array(
  185. * 'checkbox' => '<div id="{:name}" class="ui-checkbox-element"{:options}></div>'
  186. * )));
  187. * }}}
  188. *
  189. * Now, for any calls to `$this->form->checkbox()`, your custom markup template will be applied.
  190. * This works for any `Form` method that renders HTML elements.
  191. *
  192. * @see lithium\template\helper\Form::$_templateMap
  193. * @param array $config An associative array where the keys are `Form` method names (or
  194. * `'templates'`, to include a template-overriding sub-array), and the
  195. * values are arrays of configuration options to be included in the `$options`
  196. * parameter of each method specified.
  197. * @return array Returns an array containing the currently set per-method configurations, and
  198. * an array of the currently set template overrides (in the `'templates'` array key).
  199. */
  200. public function config(array $config = array()) {
  201. if (!$config) {
  202. $keys = array('base' => '', 'text' => '', 'textarea' => '', 'attributes' => '');
  203. return array('templates' => $this->_templateMap) + array_intersect_key(
  204. $this->_config, $keys
  205. );
  206. }
  207. if (isset($config['templates'])) {
  208. $this->_templateMap = $config['templates'] + $this->_templateMap;
  209. unset($config['templates']);
  210. }
  211. return ($this->_config = Set::merge($this->_config, $config)) + array(
  212. 'templates' => $this->_templateMap
  213. );
  214. }
  215. /**
  216. * Creates an HTML form, and optionally binds it to a data object which contains information on
  217. * how to render form fields, any data to pre-populate the form with, and any validation errors.
  218. * Typically, a data object will be a `Record` object returned from a `Model`, but you can
  219. * define your own custom objects as well. For more information on custom data objects, see
  220. * `lithium\template\helper\Form::$_binding`.
  221. *
  222. * @see lithium\template\helper\Form::$_binding
  223. * @see lithium\data\Entity
  224. * @param object $binding The object to bind the form to. This is usually an instance of
  225. * `Record` or `Document`, or some other class that extends
  226. * `lithium\data\Entity`.
  227. * @param array $options Other parameters for creating the form. Available options are:
  228. * - `'url'` _mixed_: A string URL or URL array parameters defining where in the
  229. * application the form should be submitted to.
  230. * - `'action'` _string_: This is a shortcut to be used if you wish to only
  231. * specify the name of the action to submit to, and use the default URL
  232. * parameters (i.e. the current controller, etc.) for generating the remainder
  233. * of the URL. Ignored if the `'url'` key is set.
  234. * - `'type'` _string_: Currently the only valid option is `'file'`. Set this if
  235. * the form will be used for file uploads.
  236. * - `'method'` _string_: Represents the HTTP method with which the form will be
  237. * submitted (`'get'`, `'post'`, `'put'` or `'delete'`). If `'put'` or
  238. * `'delete'`, the request method is simulated using a hidden input field.
  239. * @return string Returns a `<form />` open tag with the `action` attribute defined by either
  240. * the `'action'` or `'url'` options (defaulting to the current page if none is
  241. * specified), the HTTP method is defined by the `'method'` option, and any HTML
  242. * attributes passed in `$options`.
  243. * @filter
  244. */
  245. public function create($binding = null, array $options = array()) {
  246. $request = $this->_context ? $this->_context->request() : null;
  247. $defaults = array(
  248. 'url' => $request ? $request->params : array(),
  249. 'type' => null,
  250. 'action' => null,
  251. 'method' => $binding ? ($binding->exists() ? 'put' : 'post') : 'post'
  252. );
  253. list(, $options, $tpl) = $this->_defaults(__FUNCTION__, null, $options);
  254. list($scope, $options) = $this->_options($defaults, $options);
  255. $_binding =& $this->_binding;
  256. $_options =& $this->_bindingOptions;
  257. $params = compact('scope', 'options', 'binding');
  258. $extra = array('method' => __METHOD__) + compact('tpl', 'defaults');
  259. $filter = function($self, $params) use ($extra, &$_binding, &$_options) {
  260. $scope = $params['scope'];
  261. $options = $params['options'];
  262. $_binding = $params['binding'];
  263. $append = null;
  264. $scope['method'] = strtolower($scope['method']);
  265. if ($scope['type'] == 'file') {
  266. if ($scope['method'] == 'get') {
  267. $scope['method'] = 'post';
  268. }
  269. $options['enctype'] = 'multipart/form-data';
  270. }
  271. if (!($scope['method'] == 'get' || $scope['method'] == 'post')) {
  272. $append = $self->hidden('_method', array('value' => strtoupper($scope['method'])));
  273. $scope['method'] = 'post';
  274. }
  275. $url = $scope['action'] ? array('action' => $scope['action']) : $scope['url'];
  276. $options['method'] = strtolower($scope['method']);
  277. $args = array($extra['method'], $extra['tpl'], compact('url', 'options', 'append'));
  278. $_options = $scope + $options;
  279. return $self->invokeMethod('_render', $args);
  280. };
  281. return $this->_filter(__METHOD__, $params, $filter);
  282. }
  283. /**
  284. * Echoes a closing `</form>` tag and unbinds the `Form` helper from any `Record` or `Document`
  285. * object used to generate the corresponding form.
  286. *
  287. * @return string Returns a closing `</form>` tag.
  288. * @filter
  289. */
  290. public function end() {
  291. list(, $options, $template) = $this->_defaults(__FUNCTION__, null, array());
  292. $params = compact('options', 'template');
  293. $_binding =& $this->_binding;
  294. $_context =& $this->_context;
  295. $_options =& $this->_bindingOptions;
  296. $filter = function($self, $params) use (&$_binding, &$_context, &$_options, $template) {
  297. unset($_binding);
  298. $_options = array();
  299. return $self->invokeMethod('_render', array('end', $params['template'], array()));
  300. };
  301. $result = $this->_filter(__METHOD__, $params, $filter);
  302. unset($this->_binding);
  303. $this->_binding = null;
  304. return $result;
  305. }
  306. /**
  307. * Returns the entity that the `Form` helper is currently bound to.
  308. *
  309. * @see lithium\template\helper\Form::$_binding
  310. * @return object Returns an object, usually an instance of `lithium\data\Entity`.
  311. */
  312. public function binding() {
  313. return $this->_binding;
  314. }
  315. /**
  316. * Implements alternative input types as method calls against `Form` helper. Enables the
  317. * generation of HTML5 input types and other custom input types:
  318. *
  319. * {{{ embed:lithium\tests\cases\template\helper\FormTest::testCustomInputTypes(1-2) }}}
  320. *
  321. * @param string $type The method called, which represents the `type` attribute of the
  322. * `<input />` tag.
  323. * @param array $params An array of method parameters passed to the method call. The first
  324. * element should be the name of the input field, and the second should be an array
  325. * of element attributes.
  326. * @return string Returns an `<input />` tag of the type specified in `$type`.
  327. */
  328. public function __call($type, array $params = array()) {
  329. $params += array(null, array());
  330. list($name, $options) = $params;
  331. list($name, $options, $template) = $this->_defaults($type, $name, $options);
  332. $template = $this->_context->strings($template) ? $template : 'input';
  333. return $this->_render($type, $template, compact('type', 'name', 'options', 'value'));
  334. }
  335. /**
  336. * Generates a form field with a label, input, and error message (if applicable), all contained
  337. * within a wrapping element.
  338. *
  339. * {{{
  340. * echo $this->form->field('name');
  341. * echo $this->form->field('present', array('type' => 'checkbox'));
  342. * echo $this->form->field(array('email' => 'Enter a valid email'));
  343. * echo $this->form->field(array('name','email','phone'), array('div' => false));
  344. * }}}
  345. * @param mixed $name The name of the field to render. If the form was bound to an object
  346. * passed in `create()`, `$name` should be the name of a field in that object.
  347. * Otherwise, can be any arbitrary field name, as it will appear in POST data.
  348. * Alternatively supply an array of fields that will use the same options
  349. * array($field1 => $label1, $field2, $field3 => $label3)
  350. * @param array $options Rendering options for the form field. The available options are as
  351. * follows:
  352. * - `'label'` _mixed_: A string or array defining the label text and / or
  353. * parameters. By default, the label text is a human-friendly version of `$name`.
  354. * However, you can specify the label manually as a string, or both the label
  355. * text and options as an array, i.e.:
  356. * `array('label text' => array('class' => 'foo', 'any' => 'other options'))`.
  357. * - `'type'` _string_: The type of form field to render. Available default options
  358. * are: `'text'`, `'textarea'`, `'select'`, `'checkbox'`, `'password'` or
  359. * `'hidden'`, as well as any arbitrary type (i.e. HTML5 form fields).
  360. * - `'template'` _string_: Defaults to `'template'`, but can be set to any named
  361. * template string, or an arbitrary HTML fragment. For example, to change the
  362. * default wrapper tag from `<div />` to `<li />`, you can pass the following:
  363. * `'<li{:wrap}>{:label}{:input}{:error}</li>'`.
  364. * - `'wrap'` _array_: An array of HTML attributes which will be embedded in the
  365. * wrapper tag.
  366. * - `list` _array_: If `'type'` is set to `'select'`, `'list'` is an array of
  367. * key/value pairs representing the `$list` parameter of the `select()` method.
  368. * @return string Returns a form input (the input type is based on the `'type'` option), with
  369. * label and error message, wrapped in a `<div />` element.
  370. */
  371. public function field($name, array $options = array()) {
  372. if (is_array($name)) {
  373. return $this->_fields($name, $options);
  374. }
  375. list(, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  376. $defaults = array(
  377. 'label' => null,
  378. 'type' => isset($options['list']) ? 'select' : 'text',
  379. 'template' => $template,
  380. 'wrap' => array(),
  381. 'list' => null
  382. );
  383. list($options, $field) = $this->_options($defaults, $options);
  384. $label = $input = null;
  385. $wrap = $options['wrap'];
  386. $type = $options['type'];
  387. $list = $options['list'];
  388. $template = $options['template'];
  389. $notText = $template == 'field' && $type != 'text';
  390. if ($notText && $this->_context->strings('field-' . $type)) {
  391. $template = 'field-' . $type;
  392. }
  393. if (($options['label'] === null || $options['label']) && $options['type'] != 'hidden') {
  394. if (!$options['label']) {
  395. $options['label'] = Inflector::humanize(preg_replace('/[\[\]\.]/', '_', $name));
  396. }
  397. $label = $this->label(isset($options['id']) ? $options['id'] : '', $options['label']);
  398. }
  399. $call = ($type == 'select') ? array($name, $list, $field) : array($name, $field);
  400. $input = call_user_func_array(array($this, $type), $call);
  401. $error = ($this->_binding) ? $this->error($name) : null;
  402. return $this->_render(__METHOD__, $template, compact('wrap', 'label', 'input', 'error'));
  403. }
  404. /**
  405. * Helper method used by `Form::field()` for iterating over an array of multiple fields.
  406. *
  407. * @see lithium\template\helper\Form::field()
  408. * @param array $fields An array of fields to render.
  409. * @param array $options The array of options to apply to all fields in the `$fields` array. See
  410. * the `$options` parameter of the `field` method for more information.
  411. * @return string Returns the fields rendered by `field()`, each separated by a newline.
  412. */
  413. protected function _fields(array $fields, array $options = array()) {
  414. $result = array();
  415. foreach ($fields as $field => $label) {
  416. if (is_numeric($field)) {
  417. $field = $label;
  418. unset($label);
  419. }
  420. $result[] = $this->field($field, compact('label') + $options);
  421. }
  422. return join("\n", $result);
  423. }
  424. /**
  425. * Generates an HTML `<input type="submit" />` object.
  426. *
  427. * @param string $title The title of the submit button.
  428. * @param array $options Any options passed are converted to HTML attributes within the
  429. * `<input />` tag.
  430. * @return string Returns a submit `<input />` tag with the given title and HTML attributes.
  431. */
  432. public function submit($title = null, array $options = array()) {
  433. list($name, $options, $template) = $this->_defaults(__FUNCTION__, null, $options);
  434. return $this->_render(__METHOD__, $template, compact('title', 'options'));
  435. }
  436. /**
  437. * Generates an HTML `<textarea>...</textarea>` object.
  438. *
  439. * @param string $name The name of the field.
  440. * @param array $options The options to be used when generating the `<textarea />` tag pair,
  441. * which are as follows:
  442. * - `'value'` _string_: The content value of the field.
  443. * - Any other options specified are rendered as HTML attributes of the element.
  444. * @return string Returns a `<textarea>` tag with the given name and HTML attributes.
  445. */
  446. public function textarea($name, array $options = array()) {
  447. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  448. list($scope, $options) = $this->_options(array('value' => null), $options);
  449. $value = isset($scope['value']) ? $scope['value'] : '';
  450. return $this->_render(__METHOD__, $template, compact('name', 'options', 'value'));
  451. }
  452. /**
  453. * Generates an HTML `<input type="text" />` object.
  454. *
  455. * @param string $name The name of the field.
  456. * @param array $options All options passed are rendered as HTML attributes.
  457. * @return string Returns a `<input />` tag with the given name and HTML attributes.
  458. */
  459. public function text($name, array $options = array()) {
  460. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  461. return $this->_render(__METHOD__, $template, compact('name', 'options'));
  462. }
  463. /**
  464. * Generates a `<select />` list using the `$list` parameter for the `<option />` tags. The
  465. * default selection will be set to the value of `$options['value']`, if specified.
  466. *
  467. * For example: {{{
  468. * $this->form->select('colors', array(1 => 'red', 2 => 'green', 3 => 'blue'), array(
  469. * 'id' => 'Colors', 'value' => 2
  470. * ));
  471. * // Renders a '<select />' list with options 'red', 'green' and 'blue', with the 'green'
  472. * // option as the selection
  473. * }}}
  474. *
  475. * @param string $name The `name` attribute of the `<select />` element.
  476. * @param array $list An associative array of key/value pairs, which will be used to render the
  477. * list of options.
  478. * @param array $options Any HTML attributes that should be associated with the `<select />`
  479. * element. If the `'value'` key is set, this will be the value of the option
  480. * that is selected by default.
  481. * @return string Returns an HTML `<select />` element.
  482. */
  483. public function select($name, $list = array(), array $options = array()) {
  484. $defaults = array('empty' => false, 'value' => null);
  485. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  486. list($scope, $options) = $this->_options($defaults, $options);
  487. if ($scope['empty']) {
  488. $list = array('' => ($scope['empty'] === true) ? '' : $scope['empty']) + $list;
  489. }
  490. if ($template == __FUNCTION__ && $scope['multiple']) {
  491. $template = 'select-multi';
  492. }
  493. $raw = $this->_selectOptions($list, $scope);
  494. return $this->_render(__METHOD__, $template, compact('name', 'options', 'raw'));
  495. }
  496. /**
  497. * Generator method used by `select()` to produce `<option />` and `<optgroup />` elements.
  498. * Generally, this method should not need to be called directly, but through `select()`.
  499. *
  500. * @param array $list Either a flat key/value array of select menu options, or an array which
  501. * contains key/value elements and/or elements where the keys are `<optgroup />`
  502. * titles and the values are sub-arrays of key/value pairs representing nested
  503. * `<option />` elements.
  504. * @param array $scope An array of options passed to the parent scope, including the currently
  505. * selected value of the associated form element.
  506. * @return string Returns a string of `<option />` and (optionally) `<optgroup />` tags to be
  507. * embedded in a select element.
  508. */
  509. protected function _selectOptions(array $list, array $scope) {
  510. $result = "";
  511. foreach ($list as $value => $title) {
  512. if (is_array($title)) {
  513. $label = $value;
  514. $options = array();
  515. $raw = $this->_selectOptions($title, $scope);
  516. $params = compact('label', 'options', 'raw');
  517. $result .= $this->_render('select', 'option-group', $params);
  518. continue;
  519. }
  520. $selected = (
  521. (is_array($scope['value']) && in_array($value, $scope['value'])) ||
  522. ($scope['value'] == $value)
  523. );
  524. $options = $selected ? array('selected' => true) : array();
  525. $params = compact('value', 'title', 'options');
  526. $result .= $this->_render('select', 'select-option', $params);
  527. }
  528. return $result;
  529. }
  530. /**
  531. * Generates an HTML `<input type="checkbox" />` object.
  532. *
  533. * @param string $name The name of the field.
  534. * @param array $options Options to be used when generating the checkbox `<input />` element:
  535. * - `'checked'` _boolean_: Whether or not the field should be checked by default.
  536. * - `'value'` _mixed_: if specified, it will be used as the 'value' html
  537. * attribute and no hidden input field will be added.
  538. * - Any other options specified are rendered as HTML attributes of the element.
  539. * @return string Returns a `<input />` tag with the given name and HTML attributes.
  540. */
  541. public function checkbox($name, array $options = array()) {
  542. $defaults = array('value' => '1', 'hidden' => true);
  543. $options += $defaults;
  544. $default = $options['value'];
  545. $out = '';
  546. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  547. list($scope, $options) = $this->_options($defaults, $options);
  548. if (!isset($options['checked'])) {
  549. if ($this->_binding && $bound = $this->_binding->data($name)) {
  550. $options['checked'] = ($bound == $default);
  551. }
  552. }
  553. if ($scope['hidden']) {
  554. $out = $this->hidden($name, array('value' => '', 'id' => false));
  555. }
  556. $options['value'] = $scope['value'];
  557. return $out . $this->_render(__METHOD__, $template, compact('name', 'options'));
  558. }
  559. /**
  560. * Generates an HTML `<input type="radio" />` object.
  561. *
  562. * @param string $name The name of the field
  563. * @param array $options All options to be used when generating the radio `<input />` element:
  564. * - `'checked'` _boolean_: Whether or not the field should be selected by default.
  565. * - `'value'` _mixed_: if specified, it will be used as the 'value' html
  566. * attribute. Defaults to `1`
  567. * - Any other options specified are rendered as HTML attributes of the element.
  568. * @return string Returns a `<input />` tag with the given name and attributes
  569. */
  570. public function radio($name, array $options = array()) {
  571. $defaults = array('value' => '1');
  572. $options += $defaults;
  573. $default = $options['value'];
  574. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  575. list($scope, $options) = $this->_options($defaults, $options);
  576. if (!isset($options['checked'])) {
  577. if ($this->_binding && $bound = $this->_binding->data($name)) {
  578. $options['checked'] = ($bound == $default);
  579. }
  580. }
  581. $options['value'] = $scope['value'];
  582. return $this->_render(__METHOD__, $template, compact('name', 'options'));
  583. }
  584. /**
  585. * Generates an HTML `<input type="password" />` object.
  586. *
  587. * @param string $name The name of the field.
  588. * @param array $options An array of HTML attributes with which the field should be rendered.
  589. * @return string Returns a `<input />` tag with the given name and HTML attributes.
  590. */
  591. public function password($name, array $options = array()) {
  592. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  593. unset($options['value']);
  594. return $this->_render(__METHOD__, $template, compact('name', 'options'));
  595. }
  596. /**
  597. * Generates an HTML `<input type="hidden" />` object.
  598. *
  599. * @param string $name The name of the field.
  600. * @param array $options An array of HTML attributes with which the field should be rendered.
  601. * @return string Returns a `<input />` tag with the given name and HTML attributes.
  602. */
  603. public function hidden($name, array $options = array()) {
  604. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  605. return $this->_render(__METHOD__, $template, compact('name', 'options'));
  606. }
  607. /**
  608. * Generates an HTML `<label></label>` object.
  609. *
  610. * @param string $id The DOM ID of the field that the label is for.
  611. * @param string $title The content inside the `<label></label>` object.
  612. * @param array $options Besides HTML attributes, this parameter allows one additional flag:
  613. * - `'escape'` _boolean_: Defaults to `true`. Indicates whether the title of the
  614. * label should be escaped. If `false`, it will be treated as raw HTML.
  615. * @return string Returns a `<label>` tag for the name and with HTML attributes.
  616. */
  617. public function label($id, $title = null, array $options = array()) {
  618. $defaults = array('escape' => true);
  619. if (is_array($title)) {
  620. list($title, $options) = each($title);
  621. }
  622. $title = $title ?: Inflector::humanize(str_replace('.', '_', $id));
  623. list($name, $options, $template) = $this->_defaults(__FUNCTION__, $id, $options);
  624. list($scope, $options) = $this->_options($defaults, $options);
  625. if (strpos($id, '.')) {
  626. $generator = $this->_config['attributes']['id'];
  627. $id = $generator(__METHOD__, $id, $options);
  628. }
  629. return $this->_render(__METHOD__, $template, compact('id', 'title', 'options'), $scope);
  630. }
  631. /**
  632. * Generates an error message for a field which is part of an object bound to a form in
  633. * `create()`.
  634. *
  635. * @param string $name The name of the field for which to render an error.
  636. * @param mixed $key If more than one error is present for `$name`, a key may be specified.
  637. * If `$key` is not set in the array of errors, or if `$key` is `true`, the first
  638. * available error is used.
  639. * @param array $options Any rendering options or HTML attributes to be used when rendering
  640. * the error.
  641. * @return string Returns a rendered error message based on the `'error'` string template.
  642. */
  643. public function error($name, $key = null, array $options = array()) {
  644. $defaults = array('class' => 'error');
  645. list(, $options, $template) = $this->_defaults(__FUNCTION__, $name, $options);
  646. $options += $defaults;
  647. $_binding =& $this->_binding;
  648. $params = compact('name', 'key', 'options', 'template');
  649. return $this->_filter(__METHOD__, $params, function($self, $params) use (&$_binding) {
  650. $options = $params['options'];
  651. $template = $params['template'];
  652. if (isset($options['value'])) {
  653. unset($options['value']);
  654. }
  655. if (!$_binding || !$content = $_binding->errors($params['name'])) {
  656. return null;
  657. }
  658. $result = '';
  659. if (!is_array($content)) {
  660. $args = array(__METHOD__, $template, compact('content', 'options'));
  661. return $self->invokeMethod('_render', $args);
  662. }
  663. $errors = $content;
  664. if ($params['key'] === null) {
  665. foreach ($errors as $content) {
  666. $args = array(__METHOD__, $template, compact('content', 'options'));
  667. $result .= $self->invokeMethod('_render', $args);
  668. }
  669. return $result;
  670. }
  671. $key = $params['key'];
  672. $content = !isset($errors[$key]) || $key === true ? reset($errors) : $errors[$key];
  673. $args = array(__METHOD__, $template, compact('content', 'options'));
  674. return $self->invokeMethod('_render', $args);
  675. });
  676. }
  677. /**
  678. * Builds the defaults array for a method by name, according to the config.
  679. *
  680. * @param string $method The name of the method to create defaults for.
  681. * @param string $name The `$name` supplied to the original method.
  682. * @param string $options `$options` from the original method.
  683. * @return array Defaults array contents.
  684. */
  685. protected function _defaults($method, $name, $options) {
  686. $methodConfig = isset($this->_config[$method]) ? $this->_config[$method] : array();
  687. $options += $methodConfig + $this->_config['base'];
  688. $options = $this->_generators($method, $name, $options);
  689. $hasValue = (
  690. (!isset($options['value']) || $options['value'] === null) &&
  691. $name && $this->_binding && $value = $this->_binding->data($name)
  692. );
  693. if ($hasValue) {
  694. $options['value'] = $value;
  695. }
  696. if (isset($options['default']) && empty($options['value'])) {
  697. $options['value'] = $options['default'];
  698. }
  699. unset($options['default']);
  700. $generator = $this->_config['attributes']['name'];
  701. $name = $generator($method, $name, $options);
  702. $tplKey = isset($options['template']) ? $options['template'] : $method;
  703. $template = isset($this->_templateMap[$tplKey]) ? $this->_templateMap[$tplKey] : $tplKey;
  704. return array($name, $options, $template);
  705. }
  706. /**
  707. * Iterates over the configured attribute generators, and modifies the settings for a tag.
  708. *
  709. * @param string $method The name of the helper method which was called, i.e. `'text'`,
  710. * `'select'`, etc.
  711. * @param string $name The name of the field whose attributes are being generated. Some helper
  712. * methods, such as `create()` and `end()`, are not field-based, and therefore
  713. * will have no name.
  714. * @param array $options The options and HTML attributes that will be used to generate the
  715. * helper output.
  716. * @return array Returns the value of the `$options` array, modified by the attribute generators
  717. * added in the `'attributes'` key of the helper's configuration. Note that if a
  718. * generator is present for a field whose value is `false`, that field will be removed
  719. * from the array.
  720. */
  721. protected function _generators($method, $name, $options) {
  722. foreach ($this->_config['attributes'] as $key => $generator) {
  723. if ($key == 'name') {
  724. continue;
  725. }
  726. if ($generator && !isset($options[$key])) {
  727. if (($attr = $generator($method, $name, $options)) !== null) {
  728. $options[$key] = $attr;
  729. }
  730. continue;
  731. }
  732. if ($generator && $options[$key] === false) {
  733. unset($options[$key]);
  734. }
  735. }
  736. return $options;
  737. }
  738. }
  739. ?>