PageRenderTime 75ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/src/View/Helper/FormHelper.php

https://github.com/ceeram/cakephp
PHP | 2527 lines | 1352 code | 212 blank | 963 comment | 220 complexity | 18b5d20d6dbf1f9eb6109104389c8785 MD5 | raw file
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 0.10.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\View\Helper;
  16. use Cake\Collection\Collection;
  17. use Cake\Core\Configure;
  18. use Cake\Core\Exception\Exception;
  19. use Cake\Form\Form;
  20. use Cake\ORM\Entity;
  21. use Cake\Routing\Router;
  22. use Cake\Utility\Hash;
  23. use Cake\Utility\Inflector;
  24. use Cake\Utility\Security;
  25. use Cake\View\Form\ArrayContext;
  26. use Cake\View\Form\ContextInterface;
  27. use Cake\View\Form\EntityContext;
  28. use Cake\View\Form\FormContext;
  29. use Cake\View\Form\NullContext;
  30. use Cake\View\Helper;
  31. use Cake\View\Helper\IdGeneratorTrait;
  32. use Cake\View\StringTemplateTrait;
  33. use Cake\View\View;
  34. use Cake\View\Widget\WidgetRegistry;
  35. use DateTime;
  36. use Traversable;
  37. /**
  38. * Form helper library.
  39. *
  40. * Automatic generation of HTML FORMs from given data.
  41. *
  42. * @property HtmlHelper $Html
  43. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html
  44. */
  45. class FormHelper extends Helper
  46. {
  47. use IdGeneratorTrait;
  48. use StringTemplateTrait;
  49. /**
  50. * Other helpers used by FormHelper
  51. *
  52. * @var array
  53. */
  54. public $helpers = ['Url', 'Html'];
  55. /**
  56. * The various pickers that make up a datetime picker.
  57. *
  58. * @var array
  59. */
  60. protected $_datetimeParts = ['year', 'month', 'day', 'hour', 'minute', 'second', 'meridian'];
  61. /**
  62. * Special options used for datetime inputs.
  63. *
  64. * @var array
  65. */
  66. protected $_datetimeOptions = [
  67. 'interval', 'round', 'monthNames', 'minYear', 'maxYear',
  68. 'orderYear', 'timeFormat', 'second'
  69. ];
  70. /**
  71. * Default config for the helper.
  72. *
  73. * @var array
  74. */
  75. protected $_defaultConfig = [
  76. 'errorClass' => 'form-error',
  77. 'typeMap' => [
  78. 'string' => 'text', 'datetime' => 'datetime', 'boolean' => 'checkbox',
  79. 'timestamp' => 'datetime', 'text' => 'textarea', 'time' => 'time',
  80. 'date' => 'date', 'float' => 'number', 'integer' => 'number',
  81. 'decimal' => 'number', 'binary' => 'file', 'uuid' => 'string'
  82. ],
  83. 'templates' => [
  84. 'button' => '<button{{attrs}}>{{text}}</button>',
  85. 'checkbox' => '<input type="checkbox" name="{{name}}" value="{{value}}"{{attrs}}>',
  86. 'checkboxFormGroup' => '{{label}}',
  87. 'checkboxWrapper' => '<div class="checkbox">{{label}}</div>',
  88. 'dateWidget' => '{{year}}{{month}}{{day}}{{hour}}{{minute}}{{second}}{{meridian}}',
  89. 'error' => '<div class="error-message">{{content}}</div>',
  90. 'errorList' => '<ul>{{content}}</ul>',
  91. 'errorItem' => '<li>{{text}}</li>',
  92. 'file' => '<input type="file" name="{{name}}"{{attrs}}>',
  93. 'fieldset' => '<fieldset>{{content}}</fieldset>',
  94. 'formStart' => '<form{{attrs}}>',
  95. 'formEnd' => '</form>',
  96. 'formGroup' => '{{label}}{{input}}',
  97. 'hiddenBlock' => '<div style="display:none;">{{content}}</div>',
  98. 'input' => '<input type="{{type}}" name="{{name}}"{{attrs}}>',
  99. 'inputSubmit' => '<input type="{{type}}"{{attrs}}>',
  100. 'inputContainer' => '<div class="input {{type}}{{required}}">{{content}}</div>',
  101. 'inputContainerError' => '<div class="input {{type}}{{required}} error">{{content}}{{error}}</div>',
  102. 'label' => '<label{{attrs}}>{{text}}</label>',
  103. 'nestingLabel' => '{{hidden}}<label{{attrs}}>{{input}}{{text}}</label>',
  104. 'legend' => '<legend>{{text}}</legend>',
  105. 'option' => '<option value="{{value}}"{{attrs}}>{{text}}</option>',
  106. 'optgroup' => '<optgroup label="{{label}}"{{attrs}}>{{content}}</optgroup>',
  107. 'select' => '<select name="{{name}}"{{attrs}}>{{content}}</select>',
  108. 'selectMultiple' => '<select name="{{name}}[]" multiple="multiple"{{attrs}}>{{content}}</select>',
  109. 'radio' => '<input type="radio" name="{{name}}" value="{{value}}"{{attrs}}>',
  110. 'radioWrapper' => '{{label}}',
  111. 'textarea' => '<textarea name="{{name}}"{{attrs}}>{{value}}</textarea>',
  112. 'submitContainer' => '<div class="submit">{{content}}</div>',
  113. ]
  114. ];
  115. /**
  116. * Default widgets
  117. *
  118. * @var array
  119. */
  120. protected $_defaultWidgets = [
  121. 'button' => ['Cake\View\Widget\ButtonWidget'],
  122. 'checkbox' => ['Cake\View\Widget\CheckboxWidget'],
  123. 'file' => ['Cake\View\Widget\FileWidget'],
  124. 'label' => ['Cake\View\Widget\LabelWidget'],
  125. 'nestingLabel' => ['Cake\View\Widget\NestingLabelWidget'],
  126. 'multicheckbox' => ['Cake\View\Widget\MultiCheckboxWidget', 'nestingLabel'],
  127. 'radio' => ['Cake\View\Widget\RadioWidget', 'nestingLabel'],
  128. 'select' => ['Cake\View\Widget\SelectBoxWidget'],
  129. 'textarea' => ['Cake\View\Widget\TextareaWidget'],
  130. 'datetime' => ['Cake\View\Widget\DateTimeWidget', 'select'],
  131. '_default' => ['Cake\View\Widget\BasicWidget'],
  132. ];
  133. /**
  134. * List of fields created, used with secure forms.
  135. *
  136. * @var array
  137. */
  138. public $fields = [];
  139. /**
  140. * Constant used internally to skip the securing process,
  141. * and neither add the field to the hash or to the unlocked fields.
  142. *
  143. * @var string
  144. */
  145. const SECURE_SKIP = 'skip';
  146. /**
  147. * Defines the type of form being created. Set by FormHelper::create().
  148. *
  149. * @var string
  150. */
  151. public $requestType = null;
  152. /**
  153. * An array of field names that have been excluded from
  154. * the Token hash used by SecurityComponent's validatePost method
  155. *
  156. * @see FormHelper::_secure()
  157. * @see SecurityComponent::validatePost()
  158. * @var array
  159. */
  160. protected $_unlockedFields = [];
  161. /**
  162. * Registry for input widgets.
  163. *
  164. * @var \Cake\View\Widget\WidgetRegistry
  165. */
  166. protected $_registry;
  167. /**
  168. * Context for the current form.
  169. *
  170. * @var \Cake\View\Form\ContextInterface
  171. */
  172. protected $_context;
  173. /**
  174. * Context provider methods.
  175. *
  176. * @var array
  177. * @see addContextProvider
  178. */
  179. protected $_contextProviders = [];
  180. /**
  181. * The action attribute value of the last created form.
  182. * Used to make form/request specific hashes for SecurityComponent.
  183. *
  184. * @var string
  185. */
  186. protected $_lastAction = '';
  187. /**
  188. * Construct the widgets and binds the default context providers
  189. *
  190. * @param \Cake\View\View $View The View this helper is being attached to.
  191. * @param array $config Configuration settings for the helper.
  192. */
  193. public function __construct(View $View, array $config = [])
  194. {
  195. $registry = null;
  196. $widgets = $this->_defaultWidgets;
  197. if (isset($config['registry'])) {
  198. $registry = $config['registry'];
  199. unset($config['registry']);
  200. }
  201. if (isset($config['widgets'])) {
  202. if (is_string($config['widgets'])) {
  203. $config['widgets'] = (array)$config['widgets'];
  204. }
  205. $widgets = $config['widgets'] + $widgets;
  206. unset($config['widgets']);
  207. }
  208. parent::__construct($View, $config);
  209. $this->widgetRegistry($registry, $widgets);
  210. $this->_addDefaultContextProviders();
  211. }
  212. /**
  213. * Set the widget registry the helper will use.
  214. *
  215. * @param \Cake\View\Widget\WidgetRegistry $instance The registry instance to set.
  216. * @param array $widgets An array of widgets
  217. * @return \Cake\View\Widget\WidgetRegistry
  218. */
  219. public function widgetRegistry(WidgetRegistry $instance = null, $widgets = [])
  220. {
  221. if ($instance === null) {
  222. if ($this->_registry === null) {
  223. $this->_registry = new WidgetRegistry($this->templater(), $this->_View, $widgets);
  224. }
  225. return $this->_registry;
  226. }
  227. $this->_registry = $instance;
  228. return $this->_registry;
  229. }
  230. /**
  231. * Add the default suite of context providers provided by CakePHP.
  232. *
  233. * @return void
  234. */
  235. protected function _addDefaultContextProviders()
  236. {
  237. $this->addContextProvider('orm', function ($request, $data) {
  238. if (is_array($data['entity']) || $data['entity'] instanceof Traversable) {
  239. $pass = (new Collection($data['entity']))->first() !== null;
  240. if ($pass) {
  241. return new EntityContext($request, $data);
  242. }
  243. }
  244. if ($data['entity'] instanceof Entity) {
  245. return new EntityContext($request, $data);
  246. }
  247. if (is_array($data['entity']) && empty($data['entity']['schema'])) {
  248. return new EntityContext($request, $data);
  249. }
  250. });
  251. $this->addContextProvider('form', function ($request, $data) {
  252. if ($data['entity'] instanceof Form) {
  253. return new FormContext($request, $data);
  254. }
  255. });
  256. $this->addContextProvider('array', function ($request, $data) {
  257. if (is_array($data['entity']) && isset($data['entity']['schema'])) {
  258. return new ArrayContext($request, $data['entity']);
  259. }
  260. });
  261. }
  262. /**
  263. * Returns if a field is required to be filled based on validation properties from the validating object.
  264. *
  265. * @param \Cake\Validation\ValidationSet $validationRules Validation rules set.
  266. * @return bool true if field is required to be filled, false otherwise
  267. */
  268. protected function _isRequiredField($validationRules)
  269. {
  270. if (empty($validationRules) || count($validationRules) === 0) {
  271. return false;
  272. }
  273. $validationRules->isUpdate($this->requestType === 'put');
  274. foreach ($validationRules as $rule) {
  275. if ($rule->skip()) {
  276. continue;
  277. }
  278. return !$validationRules->isEmptyAllowed();
  279. }
  280. return false;
  281. }
  282. /**
  283. * Returns an HTML FORM element.
  284. *
  285. * ### Options:
  286. *
  287. * - `type` Form method defaults to autodetecting based on the form context. If
  288. * the form context's isCreate() method returns false, a PUT request will be done.
  289. * - `action` The controller action the form submits to, (optional). Use this option if you
  290. * don't need to change the controller from the current request's controller.
  291. * - `url` The URL the form submits to. Can be a string or a URL array. If you use 'url'
  292. * you should leave 'action' undefined.
  293. * - `encoding` Set the accept-charset encoding for the form. Defaults to `Configure::read('App.encoding')`
  294. * - `templates` The templates you want to use for this form. Any templates will be merged on top of
  295. * the already loaded templates. This option can either be a filename in /config that contains
  296. * the templates you want to load, or an array of templates to use.
  297. * - `context` Additional options for the context class. For example the EntityContext accepts a 'table'
  298. * option that allows you to set the specific Table class the form should be based on.
  299. * - `idPrefix` Prefix for generated ID attributes.
  300. *
  301. * @param mixed $model The context for which the form is being defined. Can
  302. * be an ORM entity, ORM resultset, or an array of meta data. You can use false or null
  303. * to make a model-less form.
  304. * @param array $options An array of html attributes and options.
  305. * @return string An formatted opening FORM tag.
  306. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#Cake\View\Helper\FormHelper::create
  307. */
  308. public function create($model = null, array $options = [])
  309. {
  310. $append = '';
  311. if (empty($options['context'])) {
  312. $options['context'] = [];
  313. }
  314. $options['context']['entity'] = $model;
  315. $context = $this->_getContext($options['context']);
  316. unset($options['context']);
  317. $isCreate = $context->isCreate();
  318. $options += [
  319. 'type' => $isCreate ? 'post' : 'put',
  320. 'action' => null,
  321. 'url' => null,
  322. 'encoding' => strtolower(Configure::read('App.encoding')),
  323. 'templates' => null,
  324. 'idPrefix' => null,
  325. ];
  326. $this->_idPrefix = $options['idPrefix'];
  327. $templater = $this->templater();
  328. if (!empty($options['templates'])) {
  329. $templater->push();
  330. $method = is_string($options['templates']) ? 'load' : 'add';
  331. $templater->{$method}($options['templates']);
  332. }
  333. unset($options['templates']);
  334. $url = $this->_formUrl($context, $options);
  335. $action = $this->Url->build($url);
  336. unset($options['url'], $options['action'], $options['idPrefix']);
  337. $this->_lastAction($url);
  338. $htmlAttributes = [];
  339. switch (strtolower($options['type'])) {
  340. case 'get':
  341. $htmlAttributes['method'] = 'get';
  342. break;
  343. // Set enctype for form
  344. case 'file':
  345. $htmlAttributes['enctype'] = 'multipart/form-data';
  346. $options['type'] = ($isCreate) ? 'post' : 'put';
  347. // Move on
  348. case 'post':
  349. // Move on
  350. case 'put':
  351. // Move on
  352. case 'delete':
  353. // Set patch method
  354. case 'patch':
  355. $append .= $this->hidden('_method', [
  356. 'name' => '_method',
  357. 'value' => strtoupper($options['type']),
  358. 'secure' => static::SECURE_SKIP
  359. ]);
  360. // Default to post method
  361. default:
  362. $htmlAttributes['method'] = 'post';
  363. }
  364. $this->requestType = strtolower($options['type']);
  365. if (!empty($options['encoding'])) {
  366. $htmlAttributes['accept-charset'] = $options['encoding'];
  367. }
  368. unset($options['type'], $options['encoding']);
  369. $htmlAttributes += $options;
  370. $this->fields = [];
  371. if ($this->requestType !== 'get') {
  372. $append .= $this->_csrfField();
  373. }
  374. if (!empty($append)) {
  375. $append = $templater->format('hiddenBlock', ['content' => $append]);
  376. }
  377. $actionAttr = $templater->formatAttributes(['action' => $action, 'escape' => false]);
  378. return $templater->format('formStart', [
  379. 'attrs' => $templater->formatAttributes($htmlAttributes) . $actionAttr
  380. ]) . $append;
  381. }
  382. /**
  383. * Create the URL for a form based on the options.
  384. *
  385. * @param \Cake\View\Form\ContextInterface $context The context object to use.
  386. * @param array $options An array of options from create()
  387. * @return string The action attribute for the form.
  388. */
  389. protected function _formUrl($context, $options)
  390. {
  391. if ($options['action'] === null && $options['url'] === null) {
  392. return $this->request->here(false);
  393. }
  394. if (is_string($options['url']) ||
  395. (is_array($options['url']) && isset($options['url']['_name']))
  396. ) {
  397. return $options['url'];
  398. }
  399. if (isset($options['action']) && empty($options['url']['action'])) {
  400. $options['url']['action'] = $options['action'];
  401. }
  402. $actionDefaults = [
  403. 'plugin' => $this->plugin,
  404. 'controller' => $this->request->params['controller'],
  405. 'action' => $this->request->params['action'],
  406. ];
  407. $action = (array)$options['url'] + $actionDefaults;
  408. $pk = $context->primaryKey();
  409. if (count($pk)) {
  410. $id = $context->val($pk[0]);
  411. }
  412. if (empty($action[0]) && isset($id)) {
  413. $action[0] = $id;
  414. }
  415. return $action;
  416. }
  417. /**
  418. * Correctly store the last created form action URL.
  419. *
  420. * @param string|array $url The URL of the last form.
  421. * @return void
  422. */
  423. protected function _lastAction($url)
  424. {
  425. $action = Router::url($url, true);
  426. $query = parse_url($action, PHP_URL_QUERY);
  427. $query = $query ? '?' . $query : '';
  428. $this->_lastAction = parse_url($action, PHP_URL_PATH) . $query;
  429. }
  430. /**
  431. * Return a CSRF input if the request data is present.
  432. * Used to secure forms in conjunction with CsrfComponent &
  433. * SecurityComponent
  434. *
  435. * @return string
  436. */
  437. protected function _csrfField()
  438. {
  439. if (!empty($this->request['_Token']['unlockedFields'])) {
  440. foreach ((array)$this->request['_Token']['unlockedFields'] as $unlocked) {
  441. $this->_unlockedFields[] = $unlocked;
  442. }
  443. }
  444. if (empty($this->request->params['_csrfToken'])) {
  445. return '';
  446. }
  447. return $this->hidden('_csrfToken', [
  448. 'value' => $this->request->params['_csrfToken'],
  449. 'secure' => static::SECURE_SKIP
  450. ]);
  451. }
  452. /**
  453. * Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden
  454. * input fields where appropriate.
  455. *
  456. * @param array $secureAttributes Secure attibutes which will be passed as HTML attributes
  457. * into the hidden input elements generated for the Security Component.
  458. * @return string A closing FORM tag.
  459. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#closing-the-form
  460. */
  461. public function end(array $secureAttributes = [])
  462. {
  463. $out = '';
  464. if ($this->requestType !== 'get' &&
  465. !empty($this->request['_Token'])
  466. ) {
  467. $out .= $this->secure($this->fields, $secureAttributes);
  468. $this->fields = [];
  469. }
  470. $templater = $this->templater();
  471. $out .= $templater->format('formEnd', []);
  472. $templater->pop();
  473. $this->requestType = null;
  474. $this->_context = null;
  475. $this->_idPrefix = null;
  476. return $out;
  477. }
  478. /**
  479. * Generates a hidden field with a security hash based on the fields used in
  480. * the form.
  481. *
  482. * If $secureAttributes is set, these HTML attributes will be merged into
  483. * the hidden input tags generated for the Security Component. This is
  484. * especially useful to set HTML5 attributes like 'form'.
  485. *
  486. * @param array $fields If set specifies the list of fields to use when
  487. * generating the hash, else $this->fields is being used.
  488. * @param array $secureAttributes will be passed as HTML attributes into the hidden
  489. * input elements generated for the Security Component.
  490. * @return string A hidden input field with a security hash
  491. */
  492. public function secure(array $fields = [], array $secureAttributes = [])
  493. {
  494. if (!isset($this->request['_Token']) || empty($this->request['_Token'])) {
  495. return;
  496. }
  497. $locked = [];
  498. $unlockedFields = $this->_unlockedFields;
  499. foreach ($fields as $key => $value) {
  500. if (!is_int($key)) {
  501. $locked[$key] = $value;
  502. unset($fields[$key]);
  503. }
  504. }
  505. sort($unlockedFields, SORT_STRING);
  506. sort($fields, SORT_STRING);
  507. ksort($locked, SORT_STRING);
  508. $fields += $locked;
  509. $locked = implode(array_keys($locked), '|');
  510. $unlocked = implode($unlockedFields, '|');
  511. $hashParts = [
  512. $this->_lastAction,
  513. serialize($fields),
  514. $unlocked,
  515. Security::salt()
  516. ];
  517. $fields = Security::hash(implode('', $hashParts), 'sha1');
  518. $tokenFields = array_merge($secureAttributes, [
  519. 'value' => urlencode($fields . ':' . $locked),
  520. ]);
  521. $out = $this->hidden('_Token.fields', $tokenFields);
  522. $tokenUnlocked = array_merge($secureAttributes, [
  523. 'value' => urlencode($unlocked),
  524. ]);
  525. $out .= $this->hidden('_Token.unlocked', $tokenUnlocked);
  526. return $this->formatTemplate('hiddenBlock', ['content' => $out]);
  527. }
  528. /**
  529. * Add to or get the list of fields that are currently unlocked.
  530. * Unlocked fields are not included in the field hash used by SecurityComponent
  531. * unlocking a field once its been added to the list of secured fields will remove
  532. * it from the list of fields.
  533. *
  534. * @param string|null $name The dot separated name for the field.
  535. * @return mixed Either null, or the list of fields.
  536. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#working-with-securitycomponent
  537. */
  538. public function unlockField($name = null)
  539. {
  540. if ($name === null) {
  541. return $this->_unlockedFields;
  542. }
  543. if (!in_array($name, $this->_unlockedFields)) {
  544. $this->_unlockedFields[] = $name;
  545. }
  546. $index = array_search($name, $this->fields);
  547. if ($index !== false) {
  548. unset($this->fields[$index]);
  549. }
  550. unset($this->fields[$name]);
  551. }
  552. /**
  553. * Determine which fields of a form should be used for hash.
  554. * Populates $this->fields
  555. *
  556. * @param bool $lock Whether this field should be part of the validation
  557. * or excluded as part of the unlockedFields.
  558. * @param string|array $field Reference to field to be secured. Can be dot
  559. * separated string to indicate nesting or array of fieldname parts.
  560. * @param mixed $value Field value, if value should not be tampered with.
  561. * @return mixed|null Not used yet
  562. */
  563. protected function _secure($lock, $field, $value = null)
  564. {
  565. if (is_string($field)) {
  566. $field = Hash::filter(explode('.', $field));
  567. }
  568. foreach ($this->_unlockedFields as $unlockField) {
  569. $unlockParts = explode('.', $unlockField);
  570. if (array_values(array_intersect($field, $unlockParts)) === $unlockParts) {
  571. return;
  572. }
  573. }
  574. $field = implode('.', $field);
  575. $field = preg_replace('/(\.\d+)+$/', '', $field);
  576. if ($lock) {
  577. if (!in_array($field, $this->fields)) {
  578. if ($value !== null) {
  579. return $this->fields[$field] = $value;
  580. }
  581. $this->fields[] = $field;
  582. }
  583. } else {
  584. $this->unlockField($field);
  585. }
  586. }
  587. /**
  588. * Returns true if there is an error for the given field, otherwise false
  589. *
  590. * @param string $field This should be "modelname.fieldname"
  591. * @return bool If there are errors this method returns true, else false.
  592. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#displaying-and-checking-errors
  593. */
  594. public function isFieldError($field)
  595. {
  596. return $this->_getContext()->hasError($field);
  597. }
  598. /**
  599. * Returns a formatted error message for given form field, '' if no errors.
  600. *
  601. * Uses the `error`, `errorList` and `errorItem` templates. The `errorList` and
  602. * `errorItem` templates are used to format multiple error messages per field.
  603. *
  604. * ### Options:
  605. *
  606. * - `escape` boolean - Whether or not to html escape the contents of the error.
  607. *
  608. * @param string $field A field name, like "modelname.fieldname"
  609. * @param string|array $text Error message as string or array of messages. If an array,
  610. * it should be a hash of key names => messages.
  611. * @param array $options See above.
  612. * @return string Formatted errors or ''.
  613. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#displaying-and-checking-errors
  614. */
  615. public function error($field, $text = null, array $options = [])
  616. {
  617. if (substr($field, -5) === '._ids') {
  618. $field = substr($field, 0, -5);
  619. }
  620. $options += ['escape' => true];
  621. $context = $this->_getContext();
  622. if (!$context->hasError($field)) {
  623. return '';
  624. }
  625. $error = (array)$context->error($field);
  626. if (is_array($text)) {
  627. $tmp = [];
  628. foreach ($error as $e) {
  629. if (isset($text[$e])) {
  630. $tmp[] = $text[$e];
  631. } else {
  632. $tmp[] = $e;
  633. }
  634. }
  635. $text = $tmp;
  636. }
  637. if ($text !== null) {
  638. $error = $text;
  639. }
  640. if ($options['escape']) {
  641. $error = h($error);
  642. unset($options['escape']);
  643. }
  644. if (is_array($error)) {
  645. if (count($error) > 1) {
  646. $errorText = [];
  647. foreach ($error as $err) {
  648. $errorText[] = $this->formatTemplate('errorItem', ['text' => $err]);
  649. }
  650. $error = $this->formatTemplate('errorList', [
  651. 'content' => implode('', $errorText)
  652. ]);
  653. } else {
  654. $error = array_pop($error);
  655. }
  656. }
  657. return $this->formatTemplate('error', ['content' => $error]);
  658. }
  659. /**
  660. * Returns a formatted LABEL element for HTML forms.
  661. *
  662. * Will automatically generate a `for` attribute if one is not provided.
  663. *
  664. * ### Options
  665. *
  666. * - `for` - Set the for attribute, if its not defined the for attribute
  667. * will be generated from the $fieldName parameter using
  668. * FormHelper::_domId().
  669. *
  670. * Examples:
  671. *
  672. * The text and for attribute are generated off of the fieldname
  673. *
  674. * ```
  675. * echo $this->Form->label('published');
  676. * <label for="PostPublished">Published</label>
  677. * ```
  678. *
  679. * Custom text:
  680. *
  681. * ```
  682. * echo $this->Form->label('published', 'Publish');
  683. * <label for="published">Publish</label>
  684. * ```
  685. *
  686. * Custom attributes:
  687. *
  688. * ```
  689. * echo $this->Form->label('published', 'Publish', [
  690. * 'for' => 'post-publish'
  691. * ]);
  692. * <label for="post-publish">Publish</label>
  693. * ```
  694. *
  695. * Nesting an input tag:
  696. *
  697. * ```
  698. * echo $this->Form->label('published', 'Publish', [
  699. * 'for' => 'published',
  700. * 'input' => $this->text('published'),
  701. * ]);
  702. * <label for="post-publish">Publish <input type="text" name="published"></label>
  703. * ```
  704. *
  705. * If you want to nest inputs in the labels, you will need to modify the default templates.
  706. *
  707. * @param string $fieldName This should be "modelname.fieldname"
  708. * @param string $text Text that will appear in the label field. If
  709. * $text is left undefined the text will be inflected from the
  710. * fieldName.
  711. * @param array $options An array of HTML attributes.
  712. * @return string The formatted LABEL element
  713. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-labels
  714. */
  715. public function label($fieldName, $text = null, array $options = [])
  716. {
  717. if ($text === null) {
  718. $text = $fieldName;
  719. if (substr($text, -5) === '._ids') {
  720. $text = substr($text, 0, -5);
  721. }
  722. if (strpos($text, '.') !== false) {
  723. $fieldElements = explode('.', $text);
  724. $text = array_pop($fieldElements);
  725. }
  726. if (substr($text, -3) === '_id') {
  727. $text = substr($text, 0, -3);
  728. }
  729. $text = __(Inflector::humanize(Inflector::underscore($text)));
  730. }
  731. if (isset($options['for'])) {
  732. $labelFor = $options['for'];
  733. unset($options['for']);
  734. } else {
  735. $labelFor = $this->_domId($fieldName);
  736. }
  737. $attrs = $options + [
  738. 'for' => $labelFor,
  739. 'text' => $text,
  740. ];
  741. if (isset($options['input'])) {
  742. if (is_array($options['input'])) {
  743. $attrs = $options['input'] + $attrs;
  744. }
  745. return $this->widget('nestingLabel', $attrs);
  746. }
  747. return $this->widget('label', $attrs);
  748. }
  749. /**
  750. * Generate a set of inputs for `$fields`. If $fields is empty the fields of current model
  751. * will be used.
  752. *
  753. * You can customize individual inputs through `$fields`.
  754. * ```
  755. * $this->Form->allInputs([
  756. * 'name' => ['label' => 'custom label']
  757. * ]);
  758. * ```
  759. *
  760. * You can exclude fields by specifying them as false:
  761. *
  762. * ```
  763. * $this->Form->allInputs(['title' => false]);
  764. * ```
  765. *
  766. * In the above example, no field would be generated for the title field.
  767. *
  768. * @param array $fields An array of customizations for the fields that will be
  769. * generated. This array allows you to set custom types, labels, or other options.
  770. * @param array $options Options array. Valid keys are:
  771. * - `fieldset` Set to false to disable the fieldset.
  772. * - `legend` Set to false to disable the legend for the generated input set. Or supply a string
  773. * to customize the legend text.
  774. * @return string Completed form inputs.
  775. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#generating-entire-forms
  776. */
  777. public function allInputs(array $fields = [], array $options = [])
  778. {
  779. $context = $this->_getContext();
  780. $modelFields = $context->fieldNames();
  781. $fields = array_merge(
  782. Hash::normalize($modelFields),
  783. Hash::normalize($fields)
  784. );
  785. return $this->inputs($fields, $options);
  786. }
  787. /**
  788. * Generate a set of inputs for `$fields` wrapped in a fieldset element.
  789. *
  790. * You can customize individual inputs through `$fields`.
  791. * ```
  792. * $this->Form->inputs([
  793. * 'name' => ['label' => 'custom label'],
  794. * 'email'
  795. * ]);
  796. * ```
  797. *
  798. * @param array $fields An array of the fields to generate. This array allows you to set custom
  799. * types, labels, or other options.
  800. * @param array $options Options array. Valid keys are:
  801. * - `fieldset` Set to false to disable the fieldset.
  802. * - `legend` Set to false to disable the legend for the generated input set. Or supply a string
  803. * to customize the legend text.
  804. * @return string Completed form inputs.
  805. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#generating-entire-forms
  806. */
  807. public function inputs(array $fields, array $options = [])
  808. {
  809. $fields = Hash::normalize($fields);
  810. $out = '';
  811. foreach ($fields as $name => $opts) {
  812. if ($opts === false) {
  813. continue;
  814. }
  815. $out .= $this->input($name, (array)$opts);
  816. }
  817. return $this->fieldset($out, $options);
  818. }
  819. /**
  820. * Wrap a set of inputs in a fieldset
  821. *
  822. * @param string $fields the form inputs to wrap in a fieldset
  823. * @param array $options Options array. Valid keys are:
  824. * - `fieldset` Set to false to disable the fieldset.
  825. * - `legend` Set to false to disable the legend for the generated input set. Or supply a string
  826. * to customize the legend text.
  827. * @return string Completed form inputs.
  828. */
  829. public function fieldset($fields = '', array $options = [])
  830. {
  831. $fieldset = $legend = true;
  832. $context = $this->_getContext();
  833. $out = $fields;
  834. if (isset($options['legend'])) {
  835. $legend = $options['legend'];
  836. }
  837. if (isset($options['fieldset'])) {
  838. $fieldset = $options['fieldset'];
  839. }
  840. if ($legend === true) {
  841. $actionName = __d('cake', 'New %s');
  842. $isCreate = $context->isCreate();
  843. if (!$isCreate) {
  844. $actionName = __d('cake', 'Edit %s');
  845. }
  846. $modelName = Inflector::humanize(Inflector::singularize($this->request->params['controller']));
  847. $legend = sprintf($actionName, $modelName);
  848. }
  849. if ($fieldset) {
  850. if ($legend) {
  851. $out = $this->formatTemplate('legend', ['text' => $legend]) . $out;
  852. }
  853. $out = $this->formatTemplate('fieldset', ['content' => $out]);
  854. }
  855. return $out;
  856. }
  857. /**
  858. * Generates a form input element complete with label and wrapper div
  859. *
  860. * ### Options
  861. *
  862. * See each field type method for more information. Any options that are part of
  863. * $attributes or $options for the different **type** methods can be included in `$options` for input().
  864. * Additionally, any unknown keys that are not in the list below, or part of the selected type's options
  865. * will be treated as a regular HTML attribute for the generated input.
  866. *
  867. * - `type` - Force the type of widget you want. e.g. `type => 'select'`
  868. * - `label` - Either a string label, or an array of options for the label. See FormHelper::label().
  869. * - `options` - For widgets that take options e.g. radio, select.
  870. * - `error` - Control the error message that is produced. Set to `false` to disable any kind of error reporting (field
  871. * error and error messages).
  872. * - `empty` - String or boolean to enable empty select box options.
  873. * - `nestedInput` - Used with checkbox and radio inputs. Set to false to render inputs outside of label
  874. * elements. Can be set to true on any input to force the input inside the label. If you
  875. * enable this option for radio buttons you will also need to modify the default `radioWrapper` template.
  876. *
  877. * @param string $fieldName This should be "modelname.fieldname"
  878. * @param array $options Each type of input takes different options.
  879. * @return string Completed form widget.
  880. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-form-inputs
  881. */
  882. public function input($fieldName, array $options = [])
  883. {
  884. $options += [
  885. 'type' => null,
  886. 'label' => null,
  887. 'error' => null,
  888. 'required' => null,
  889. 'options' => null,
  890. 'templates' => [],
  891. ];
  892. $options = $this->_parseOptions($fieldName, $options);
  893. $options += ['id' => $this->_domId($fieldName)];
  894. $templater = $this->templater();
  895. $newTemplates = $options['templates'];
  896. if ($newTemplates) {
  897. $templater->push();
  898. $templateMethod = is_string($options['templates']) ? 'load' : 'add';
  899. $templater->{$templateMethod}($options['templates']);
  900. }
  901. unset($options['templates']);
  902. $error = null;
  903. $errorSuffix = '';
  904. if ($options['type'] !== 'hidden' && $options['error'] !== false) {
  905. $error = $this->error($fieldName, $options['error']);
  906. $errorSuffix = empty($error) ? '' : 'Error';
  907. unset($options['error']);
  908. }
  909. $label = $options['label'];
  910. unset($options['label']);
  911. $nestedInput = false;
  912. if ($options['type'] === 'checkbox') {
  913. $nestedInput = true;
  914. }
  915. $nestedInput = isset($options['nestedInput']) ? $options['nestedInput'] : $nestedInput;
  916. if ($nestedInput === true && $options['type'] === 'checkbox' && !array_key_exists('hiddenField', $options) && $label !== false) {
  917. $options['hiddenField'] = '_split';
  918. }
  919. $input = $this->_getInput($fieldName, $options);
  920. if ($options['type'] === 'hidden') {
  921. if ($newTemplates) {
  922. $templater->pop();
  923. }
  924. return $input;
  925. }
  926. $label = $this->_getLabel($fieldName, compact('input', 'label', 'error', 'nestedInput') + $options);
  927. $result = $this->_groupTemplate(compact('input', 'label', 'error', 'options'));
  928. $result = $this->_inputContainerTemplate([
  929. 'content' => $result,
  930. 'error' => $error,
  931. 'errorSuffix' => $errorSuffix,
  932. 'options' => $options
  933. ]);
  934. if ($newTemplates) {
  935. $templater->pop();
  936. }
  937. return $result;
  938. }
  939. /**
  940. * Generates an group template element
  941. *
  942. * @param array $options The options for group template
  943. * @return string The generated group template
  944. */
  945. protected function _groupTemplate($options)
  946. {
  947. $groupTemplate = $options['options']['type'] === 'checkbox' ? 'checkboxFormGroup' : 'formGroup';
  948. return $this->templater()->format($groupTemplate, [
  949. 'input' => $options['input'],
  950. 'label' => $options['label'],
  951. 'error' => $options['error']
  952. ]);
  953. }
  954. /**
  955. * Generates an input container template
  956. *
  957. * @param array $options The options for input container template
  958. * @return string The generated input container template
  959. */
  960. protected function _inputContainerTemplate($options)
  961. {
  962. $inputContainerTemplate = $options['options']['type'] . 'Container' . $options['errorSuffix'];
  963. if (!$this->templater()->get($inputContainerTemplate)) {
  964. $inputContainerTemplate = 'inputContainer' . $options['errorSuffix'];
  965. }
  966. return $this->templater()->format($inputContainerTemplate, [
  967. 'content' => $options['content'],
  968. 'error' => $options['error'],
  969. 'required' => $options['options']['required'] ? ' required' : '',
  970. 'type' => $options['options']['type']
  971. ]);
  972. }
  973. /**
  974. * Generates an input element
  975. *
  976. * @param string $fieldName the field name
  977. * @param array $options The options for the input element
  978. * @return string The generated input element
  979. */
  980. protected function _getInput($fieldName, $options)
  981. {
  982. switch ($options['type']) {
  983. case 'select':
  984. $opts = $options['options'];
  985. unset($options['options']);
  986. return $this->select($fieldName, $opts, $options);
  987. case 'radio':
  988. $opts = $options['options'];
  989. unset($options['options']);
  990. return $this->radio($fieldName, $opts, $options);
  991. case 'multicheckbox':
  992. $opts = $options['options'];
  993. unset($options['options']);
  994. return $this->multicheckbox($fieldName, $opts, $options);
  995. case 'url':
  996. $options = $this->_initInputField($fieldName, $options);
  997. return $this->widget($options['type'], $options);
  998. default:
  999. return $this->{$options['type']}($fieldName, $options);
  1000. }
  1001. }
  1002. /**
  1003. * Generates input options array
  1004. *
  1005. * @param string $fieldName The name of the field to parse options for.
  1006. * @param array $options Options list.
  1007. * @return array Options
  1008. */
  1009. protected function _parseOptions($fieldName, $options)
  1010. {
  1011. $needsMagicType = false;
  1012. if (empty($options['type'])) {
  1013. $needsMagicType = true;
  1014. $options['type'] = $this->_inputType($fieldName, $options);
  1015. }
  1016. $options = $this->_magicOptions($fieldName, $options, $needsMagicType);
  1017. return $options;
  1018. }
  1019. /**
  1020. * Returns the input type that was guessed for the provided fieldName,
  1021. * based on the internal type it is associated too, its name and the
  1022. * variables that can be found in the view template
  1023. *
  1024. * @param string $fieldName the name of the field to guess a type for
  1025. * @param array $options the options passed to the input method
  1026. * @return string
  1027. */
  1028. protected function _inputType($fieldName, $options)
  1029. {
  1030. $context = $this->_getContext();
  1031. if ($context->isPrimaryKey($fieldName)) {
  1032. return 'hidden';
  1033. }
  1034. if (substr($fieldName, -3) === '_id') {
  1035. return 'select';
  1036. }
  1037. $internalType = $context->type($fieldName);
  1038. $map = $this->_config['typeMap'];
  1039. $type = isset($map[$internalType]) ? $map[$internalType] : 'text';
  1040. $fieldName = array_slice(explode('.', $fieldName), -1)[0];
  1041. switch (true) {
  1042. case isset($options['checked']):
  1043. return 'checkbox';
  1044. case isset($options['options']):
  1045. return 'select';
  1046. case in_array($fieldName, ['passwd', 'password']):
  1047. return 'password';
  1048. case in_array($fieldName, ['tel', 'telephone', 'phone']):
  1049. return 'tel';
  1050. case $fieldName === 'email':
  1051. return 'email';
  1052. case isset($options['rows']) || isset($options['cols']):
  1053. return 'textarea';
  1054. }
  1055. return $type;
  1056. }
  1057. /**
  1058. * Selects the variable containing the options for a select field if present,
  1059. * and sets the value to the 'options' key in the options array.
  1060. *
  1061. * @param string $fieldName The name of the field to find options for.
  1062. * @param array $options Options list.
  1063. * @return array
  1064. */
  1065. protected function _optionsOptions($fieldName, $options)
  1066. {
  1067. if (isset($options['options'])) {
  1068. return $options;
  1069. }
  1070. $pluralize = true;
  1071. if (substr($fieldName, -5) === '._ids') {
  1072. $fieldName = substr($fieldName, 0, -5);
  1073. $pluralize = false;
  1074. } elseif (substr($fieldName, -3) === '_id') {
  1075. $fieldName = substr($fieldName, 0, -3);
  1076. }
  1077. $fieldName = array_slice(explode('.', $fieldName), -1)[0];
  1078. $varName = Inflector::variable(
  1079. $pluralize ? Inflector::pluralize($fieldName) : $fieldName
  1080. );
  1081. $varOptions = $this->_View->get($varName);
  1082. if (!is_array($varOptions) && !($varOptions instanceof Traversable)) {
  1083. return $options;
  1084. }
  1085. if ($options['type'] !== 'radio') {
  1086. $options['type'] = 'select';
  1087. }
  1088. $options['options'] = $varOptions;
  1089. return $options;
  1090. }
  1091. /**
  1092. * Magically set option type and corresponding options
  1093. *
  1094. * @param string $fieldName The name of the field to generate options for.
  1095. * @param array $options Options list.
  1096. * @param bool $allowOverride Whether or not it is allowed for this method to
  1097. * overwrite the 'type' key in options.
  1098. * @return array
  1099. */
  1100. protected function _magicOptions($fieldName, $options, $allowOverride)
  1101. {
  1102. $context = $this->_getContext();
  1103. if (!isset($options['required']) && $options['type'] !== 'hidden') {
  1104. $options['required'] = $context->isRequired($fieldName);
  1105. }
  1106. $type = $context->type($fieldName);
  1107. $fieldDef = $context->attributes($fieldName);
  1108. if ($options['type'] === 'number' && !isset($options['step'])) {
  1109. if ($type === 'decimal' && isset($fieldDef['precision'])) {
  1110. $decimalPlaces = $fieldDef['precision'];
  1111. $options['step'] = sprintf('%.' . $decimalPlaces . 'F', pow(10, -1 * $decimalPlaces));
  1112. } elseif ($type === 'float') {
  1113. $options['step'] = 'any';
  1114. }
  1115. }
  1116. $typesWithOptions = ['text', 'number', 'radio', 'select'];
  1117. $magicOptions = (in_array($options['type'], ['radio', 'select']) || $allowOverride);
  1118. if ($magicOptions && in_array($options['type'], $typesWithOptions)) {
  1119. $options = $this->_optionsOptions($fieldName, $options);
  1120. }
  1121. if ($allowOverride && substr($fieldName, -5) === '._ids') {
  1122. $options['type'] = 'select';
  1123. if (empty($options['multiple'])) {
  1124. $options['multiple'] = true;
  1125. }
  1126. }
  1127. if ($options['type'] === 'select' && array_key_exists('step', $options)) {
  1128. unset($options['step']);
  1129. }
  1130. $autoLength = !array_key_exists('maxlength', $options)
  1131. && !empty($fieldDef['length'])
  1132. && $options['type'] !== 'select';
  1133. $allowedTypes = ['text', 'textarea', 'email', 'tel', 'url', 'search'];
  1134. if ($autoLength && in_array($options['type'], $allowedTypes)) {
  1135. $options['maxlength'] = min($fieldDef['length'], 100000);
  1136. }
  1137. if (in_array($options['type'], ['datetime', 'date', 'time', 'select'])) {
  1138. $options += ['empty' => false];
  1139. }
  1140. return $options;
  1141. }
  1142. /**
  1143. * Generate label for input
  1144. *
  1145. * @param string $fieldName The name of the field to generate label for.
  1146. * @param array $options Options list.
  1147. * @return bool|string false or Generated label element
  1148. */
  1149. protected function _getLabel($fieldName, $options)
  1150. {
  1151. if ($options['type'] === 'hidden') {
  1152. return false;
  1153. }
  1154. $label = null;
  1155. if (isset($options['label'])) {
  1156. $label = $options['label'];
  1157. }
  1158. if ($label === false && $options['type'] === 'checkbox') {
  1159. return $options['input'];
  1160. }
  1161. if ($label === false) {
  1162. return false;
  1163. }
  1164. return $this->_inputLabel($fieldName, $label, $options);
  1165. }
  1166. /**
  1167. * Extracts a single option from an options array.
  1168. *
  1169. * @param string $name The name of the option to pull out.
  1170. * @param array $options The array of options you want to extract.
  1171. * @param mixed $default The default option value
  1172. * @return mixed the contents of the option or default
  1173. */
  1174. protected function _extractOption($name, $options, $default = null)
  1175. {
  1176. if (array_key_exists($name, $options)) {
  1177. return $options[$name];
  1178. }
  1179. return $default;
  1180. }
  1181. /**
  1182. * Generate a label for an input() call.
  1183. *
  1184. * $options can contain a hash of id overrides. These overrides will be
  1185. * used instead of the generated values if present.
  1186. *
  1187. * @param string $fieldName The name of the field to generate label for.
  1188. * @param string $label Label text.
  1189. * @param array $options Options for the label element.
  1190. * @return string Generated label element
  1191. */
  1192. protected function _inputLabel($fieldName, $label, $options)
  1193. {
  1194. $labelAttributes = [];
  1195. if (is_array($label)) {
  1196. $labelText = null;
  1197. if (isset($label['text'])) {
  1198. $labelText = $label['text'];
  1199. unset($label['text']);
  1200. }
  1201. $labelAttributes = array_merge($labelAttributes, $label);
  1202. } else {
  1203. $labelText = $label;
  1204. }
  1205. $options += ['id' => null, 'input' => null, 'nestedInput' => false];
  1206. $labelAttributes['for'] = $options['id'];
  1207. $groupTypes = ['radio', 'multicheckbox', 'date', 'time', 'datetime'];
  1208. if (in_array($options['type'], $groupTypes, true)) {
  1209. $labelAttributes['for'] = false;
  1210. }
  1211. if ($options['nestedInput']) {
  1212. $labelAttributes['input'] = $options['input'];
  1213. }
  1214. return $this->label($fieldName, $labelText, $labelAttributes);
  1215. }
  1216. /**
  1217. * Creates a checkbox input widget.
  1218. *
  1219. * ### Options:
  1220. *
  1221. * - `value` - the value of the checkbox
  1222. * - `checked` - boolean indicate that this checkbox is checked.
  1223. * - `hiddenField` - boolean to indicate if you want the results of checkbox() to include
  1224. * a hidden input with a value of ''.
  1225. * - `disabled` - create a disabled input.
  1226. * - `default` - Set the default value for the checkbox. This allows you to start checkboxes
  1227. * as checked, without having to check the POST data. A matching POST data value, will overwrite
  1228. * the default value.
  1229. *
  1230. * @param string $fieldName Name of a field, like this "modelname.fieldname"
  1231. * @param array $options Array of HTML attributes.
  1232. * @return string|array An HTML text input element.
  1233. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-checkboxes
  1234. */
  1235. public function checkbox($fieldName, array $options = [])
  1236. {
  1237. $options += ['hiddenField' => true, 'value' => 1];
  1238. // Work around value=>val translations.
  1239. $value = $options['value'];
  1240. unset($options['value']);
  1241. $options = $this->_initInputField($fieldName, $options);
  1242. $options['value'] = $value;
  1243. $output = '';
  1244. if ($options['hiddenField']) {
  1245. $hiddenOptions = [
  1246. 'name' => $options['name'],
  1247. 'value' => ($options['hiddenField'] !== true && $options['hiddenField'] !== '_split' ? $options['hiddenField'] : '0'),
  1248. 'form' => isset($options['form']) ? $options['form'] : null,
  1249. 'secure' => false
  1250. ];
  1251. if (isset($options['disabled']) && $options['disabled']) {
  1252. $hiddenOptions['disabled'] = 'disabled';
  1253. }
  1254. $output = $this->hidden($fieldName, $hiddenOptions);
  1255. }
  1256. if ($options['hiddenField'] === '_split') {
  1257. unset($options['hiddenField'], $options['type']);
  1258. return ['hidden' => $output, 'input' => $this->widget('checkbox', $options)];
  1259. }
  1260. unset($options['hiddenField'], $options['type']);
  1261. return $output . $this->widget('checkbox', $options);
  1262. }
  1263. /**
  1264. * Creates a set of radio widgets.
  1265. *
  1266. * ### Attributes:
  1267. *
  1268. * - `value` - Indicates the value when this radio button is checked.
  1269. * - `label` - boolean to indicate whether or not labels for widgets should be displayed.
  1270. * - `hiddenField` - boolean to indicate if you want the results of radio() to include
  1271. * a hidden input with a value of ''. This is useful for creating radio sets that are non-continuous.
  1272. * - `disabled` - Set to `true` or `disabled` to disable all the radio buttons.
  1273. * - `empty` - Set to `true` to create an input with the value '' as the first option. When `true`
  1274. * the radio label will be 'empty'. Set this option to a string to control the label value.
  1275. *
  1276. * @param string $fieldName Name of a field, like this "modelname.fieldname"
  1277. * @param array|\Traversable $options Radio button options array.
  1278. * @param array $attributes Array of HTML attributes, and special attributes above.
  1279. * @return string Completed radio widget set.
  1280. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-radio-buttons
  1281. */
  1282. public function radio($fieldName, $options = [], array $attributes = [])
  1283. {
  1284. $attributes['options'] = $options;
  1285. $attributes['idPrefix'] = $this->_idPrefix;
  1286. $attributes = $this->_initInputField($fieldName, $attributes);
  1287. $value = $attributes['val'];
  1288. $hiddenField = isset($attributes['hiddenField']) ? $attributes['hiddenField'] : true;
  1289. unset($attributes['hiddenField']);
  1290. $radio = $this->widget('radio', $attributes);
  1291. $hidden = '';
  1292. if ($hiddenField && (!isset($value) || $value === '')) {
  1293. $hidden = $this->hidden($fieldName, [
  1294. 'value' => '',
  1295. 'form' => isset($attributes['form']) ? $attributes['form'] : null,
  1296. 'name' => $attributes['name'],
  1297. ]);
  1298. }
  1299. return $hidden . $radio;
  1300. }
  1301. /**
  1302. * Missing method handler - implements various simple input types. Is used to create inputs
  1303. * of various types. e.g. `$this->Form->text();` will create `<input type="text" />` while
  1304. * `$this->Form->range();` will create `<input type="range" />`
  1305. *
  1306. * ### Usage
  1307. *
  1308. * `$this->Form->search('User.query', ['value' => 'test']);`
  1309. *
  1310. * Will make an input like:
  1311. *
  1312. * `<input type="search" id="UserQuery" name="User[query]" value="test" />`
  1313. *
  1314. * The first argument to an input type should always be the fieldname, in `Model.field` format.
  1315. * The second argument should always be an array of attributes for the input.
  1316. *
  1317. * @param string $method Method name / input type to make.
  1318. * @param array $params Parameters for the method call
  1319. * @return string Formatted input method.
  1320. * @throws \Cake\Core\Exception\Exception When there are no params for the method call.
  1321. */
  1322. public function __call($method, $params)
  1323. {
  1324. $options = [];
  1325. if (empty($params)) {
  1326. throw new Exception(sprintf('Missing field name for FormHelper::%s', $method));
  1327. }
  1328. if (isset($params[1])) {
  1329. $options = $params[1];
  1330. }
  1331. if (!isset($options['type'])) {
  1332. $options['type'] = $method;
  1333. }
  1334. $options = $this->_initInputField($params[0], $options);
  1335. return $this->widget($options['type'], $options);
  1336. }
  1337. /**
  1338. * Creates a textarea widget.
  1339. *
  1340. * ### Options:
  1341. *
  1342. * - `escape` - Whether or not the contents of the textarea should be escaped. Defaults to true.
  1343. *
  1344. * @param string $fieldName Name of a field, in the form "modelname.fieldname"
  1345. * @param array $options Array of HTML attributes, and special options above.
  1346. * @return string A generated HTML text input element
  1347. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-textareas
  1348. */
  1349. public function textarea($fieldName, array $options = [])
  1350. {
  1351. $options = $this->_initInputField($fieldName, $options);
  1352. unset($options['type']);
  1353. return $this->widget('textarea', $options);
  1354. }
  1355. /**
  1356. * Creates a hidden input field.
  1357. *
  1358. * @param string $fieldName Name of a field, in the form of "modelname.fieldname"
  1359. * @param array $options Array of HTML attributes.
  1360. * @return string A generated hidden input
  1361. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-hidden-inputs
  1362. */
  1363. public function hidden($fieldName, array $options = [])
  1364. {
  1365. $options += ['required' => false, 'secure' => true];
  1366. $secure = $options['secure'];
  1367. unset($options['secure']);
  1368. $options = $this->_initInputField($fieldName, array_merge(
  1369. $options,
  1370. ['secure' => static::SECURE_SKIP]
  1371. ));
  1372. if ($secure === true) {
  1373. $this->_secure(true, $this->_secureFieldName($options['name']), (string)$options['val']);
  1374. }
  1375. $options['type'] = 'hidden';
  1376. return $this->widget('hidden', $options);
  1377. }
  1378. /**
  1379. * Creates file input widget.
  1380. *
  1381. * @param string $fieldName Name of a field, in the form "modelname.fieldname"
  1382. * @param array $options Array of HTML attributes.
  1383. * @return string A generated file input.
  1384. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-file-inputs
  1385. */
  1386. public function file($fieldName, array $options = [])
  1387. {
  1388. $options += ['secure' => true];
  1389. $options = $this->_initInputField($fieldName, $options);
  1390. unset($options['type']);
  1391. return $this->widget('file', $options);
  1392. }
  1393. /**
  1394. * Creates a `<button>` tag.
  1395. *
  1396. * The type attribute defaults to `type="submit"`
  1397. * You can change it to a different value by using `$options['type']`.
  1398. *
  1399. * ### Options:
  1400. *
  1401. * - `escape` - HTML entity encode the $title of the button. Defaults to false.
  1402. *
  1403. * @param string $title The button's caption. Not automatically HTML encoded
  1404. * @param array $options Array of options and HTML attributes.
  1405. * @return string A HTML button tag.
  1406. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-button-elements
  1407. */
  1408. public function button($title, array $options = [])
  1409. {
  1410. $options += ['type' => 'submit', 'escape' => false, 'secure' => false];
  1411. $options['text'] = $title;
  1412. return $this->widget('button', $options);
  1413. }
  1414. /**
  1415. * Create a `<button>` tag with a surrounding `<form>` that submits via POST.
  1416. *
  1417. * This method creates a `<form>` element. So do not use this method in an already opened form.
  1418. * Instead use FormHelper::submit() or FormHelper::button() to create buttons inside opened forms.
  1419. *
  1420. * ### Options:
  1421. *
  1422. * - `data` - Array with key/value to pass in input hidden
  1423. * - Other options is the same of button method.
  1424. *
  1425. * @param string $title The button's caption. Not automatically HTML encoded
  1426. * @param string|array $url URL as string or array
  1427. * @param array $options Array of options and HTML attributes.
  1428. * @return string A HTML button tag.
  1429. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-standalone-buttons-and-post-links
  1430. */
  1431. public function postButton($title, $url, array $options = [])
  1432. {
  1433. $out = $this->create(false, ['url' => $url]);
  1434. if (isset($options['data']) && is_array($options['data'])) {
  1435. foreach (Hash::flatten($options['data']) as $key => $value) {
  1436. $out .= $this->hidden($key, ['value' => $value]);
  1437. }
  1438. unset($options['data']);
  1439. }
  1440. $out .= $this->button($title, $options);
  1441. $out .= $this->end();
  1442. return $out;
  1443. }
  1444. /**
  1445. * Creates an HTML link, but access the URL using the method you specify
  1446. * (defaults to POST). Requires javascript to be enabled in browser.
  1447. *
  1448. * This method creates a `<form>` element. So do not use this method inside an
  1449. * existing form. Instead you should add a submit button using FormHelper::submit()
  1450. *
  1451. * ### Options:
  1452. *
  1453. * - `data` - Array with key/value to pass in input hidden
  1454. * - `method` - Request method to use. Set to 'delete' to simulate
  1455. * HTTP/1.1 DELETE request. Defaults to 'post'.
  1456. * - `confirm` - Confirm message to show.
  1457. * - `block` - Set to true to append form to view block "postLink" or provide
  1458. * custom block name.
  1459. * - Other options are the same of HtmlHelper::link() method.
  1460. * - The option `onclick` will be replaced.
  1461. *
  1462. * @param string $title The content to be wrapped by <a> tags.
  1463. * @param string|array $url Cake-relative URL or array of URL parameters, or
  1464. * external URL (starts with http://)
  1465. * @param array $options Array of HTML attributes.
  1466. * @return string An `<a />` element.
  1467. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-standalone-buttons-and-post-links
  1468. */
  1469. public function postLink($title, $url = null, array $options = [])
  1470. {
  1471. $options += ['block' => null, 'confirm' => null];
  1472. $requestMethod = 'POST';
  1473. if (!empty($options['method'])) {
  1474. $requestMethod = strtoupper($options['method']);
  1475. unset($options['method']);
  1476. }
  1477. $confirmMessage = $options['confirm'];
  1478. unset($options['confirm']);
  1479. $formName = str_replace('.', '', uniqid('post_', true));
  1480. $formOptions = [
  1481. 'action' => $this->Url->build($url),
  1482. 'name' => $formName,
  1483. 'style' => 'display:none;',
  1484. 'method' => 'post',
  1485. ];
  1486. if (isset($options['target'])) {
  1487. $formOptions['target'] = $options['target'];
  1488. unset($options['target']);
  1489. }
  1490. $this->_lastAction($url);
  1491. $out = $this->formatTemplate('formStart', [
  1492. 'attrs' => $this->templater()->formatAttributes($formOptions)
  1493. ]);
  1494. $out .= $this->hidden('_method', ['value' => $requestMethod]);
  1495. $out .= $this->_csrfField();
  1496. $fields = [];
  1497. if (isset($options['data']) && is_array($options['data'])) {
  1498. foreach (Hash::flatten($options['data']) as $key => $value) {
  1499. $fields[$key] = $value;
  1500. $out .= $this->hidden($key, ['value' => $value]);
  1501. }
  1502. unset($options['data']);
  1503. }
  1504. $out .= $this->secure($fields);
  1505. $out .= $this->formatTemplate('formEnd', []);
  1506. if ($options['block']) {
  1507. if ($options['block'] === true) {
  1508. $options['block'] = __FUNCTION__;
  1509. }
  1510. $this->_View->append($options['block'], $out);
  1511. $out = '';
  1512. }
  1513. unset($options['block']);
  1514. $url = '#';
  1515. $onClick = 'document.' . $formName . '.submit();';
  1516. if ($confirmMessage) {
  1517. $options['onclick'] = $this->_confirm($confirmMessage, $onClick, '', $options);
  1518. } else {
  1519. $options['onclick'] = $onClick . ' ';
  1520. }
  1521. $options['onclick'] .= 'event.returnValue = false; return false;';
  1522. $out .= $this->Html->link($title, $url, $options);
  1523. return $out;
  1524. }
  1525. /**
  1526. * Creates a submit button element. This method will generate `<input />` elements that
  1527. * can be used to submit, and reset forms by using $options. image submits can be created by supplying an
  1528. * image path for $caption.
  1529. *
  1530. * ### Options
  1531. *
  1532. * - `type` - Set to 'reset' for reset inputs. Defaults to 'submit'
  1533. * - Other attributes will be assigned to the input element.
  1534. *
  1535. * @param string $caption The label appearing on the button OR if string contains :// or the
  1536. * extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension
  1537. * exists, AND the first character is /, image is relative to webroot,
  1538. * OR if the first character is not /, image is relative to webroot/img.
  1539. * @param array $options Array of options. See above.
  1540. * @return string A HTML submit button
  1541. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-buttons-and-submit-elements
  1542. */
  1543. public function submit($caption = null, array $options = [])
  1544. {
  1545. if (!is_string($caption) && empty($caption)) {
  1546. $caption = __d('cake', 'Submit');
  1547. }
  1548. $options += ['type' => 'submit', 'secure' => false];
  1549. if (isset($options['name'])) {
  1550. $this->_secure($options['secure'], $this->_secureFieldName($options['name']));
  1551. }
  1552. unset($options['secure']);
  1553. $isUrl = strpos($caption, '://') !== false;
  1554. $isImage = preg_match('/\.(jpg|jpe|jpeg|gif|png|ico)$/', $caption);
  1555. $type = $options['type'];
  1556. unset($options['type']);
  1557. if ($isUrl || $isImage) {
  1558. $unlockFields = ['x', 'y'];
  1559. if (isset($options['name'])) {
  1560. $unlockFields = [
  1561. $options['name'] . '_x',
  1562. $options['name'] . '_y'
  1563. ];
  1564. }
  1565. foreach ($unlockFields as $ignore) {
  1566. $this->unlockField($ignore);
  1567. }
  1568. $type = 'image';
  1569. }
  1570. if ($isUrl) {
  1571. $options['src'] = $caption;
  1572. } elseif ($isImage) {
  1573. if ($caption{0} !== '/') {
  1574. $url = $this->Url->webroot(Configure::read('App.imageBaseUrl') . $caption);
  1575. } else {
  1576. $url = $this->Url->webroot(trim($caption, '/'));
  1577. }
  1578. $url = $this->Url->assetTimestamp($url);
  1579. $options['src'] = $url;
  1580. } else {
  1581. $options['value'] = $caption;
  1582. }
  1583. $input = $this->formatTemplate('inputSubmit', [
  1584. 'type' => $type,
  1585. 'attrs' => $this->templater()->formatAttributes($options),
  1586. ]);
  1587. return $this->formatTemplate('submitContainer', [
  1588. 'content' => $input
  1589. ]);
  1590. }
  1591. /**
  1592. * Returns a formatted SELECT element.
  1593. *
  1594. * ### Attributes:
  1595. *
  1596. * - `multiple` - show a multiple select box. If set to 'checkbox' multiple checkboxes will be
  1597. * created instead.
  1598. * - `empty` - If true, the empty select option is shown. If a string,
  1599. * that string is displayed as the empty element.
  1600. * - `escape` - If true contents of options will be HTML entity encoded. Defaults to true.
  1601. * - `val` The selected value of the input.
  1602. * - `disabled` - Control the disabled attribute. When creating a select box, set to true to disable the
  1603. * select box. Set to an array to disable specific option elements.
  1604. *
  1605. * ### Using options
  1606. *
  1607. * A simple array will create normal options:
  1608. *
  1609. * ```
  1610. * $options = [1 => 'one', 2 => 'two'];
  1611. * $this->Form->select('Model.field', $options));
  1612. * ```
  1613. *
  1614. * While a nested options array will create optgroups with options inside them.
  1615. * ```
  1616. * $options = [
  1617. * 1 => 'bill',
  1618. * 'fred' => [
  1619. * 2 => 'fred',
  1620. * 3 => 'fred jr.'
  1621. * ]
  1622. * ];
  1623. * $this->Form->select('Model.field', $options);
  1624. * ```
  1625. *
  1626. * If you have multiple options that need to have the same value attribute, you can
  1627. * use an array of arrays to express this:
  1628. *
  1629. * ```
  1630. * $options = [
  1631. * ['name' => 'United states', 'value' => 'USA'],
  1632. * ['name' => 'USA', 'value' => 'USA'],
  1633. * ];
  1634. * ```
  1635. *
  1636. * @param string $fieldName Name attribute of the SELECT
  1637. * @param array|\Traversable $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the
  1638. * SELECT element
  1639. * @param array $attributes The HTML attributes of the select element.
  1640. * @return string Formatted SELECT element
  1641. * @see \Cake\View\Helper\FormHelper::multiCheckbox() for creating multiple checkboxes.
  1642. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-select-pickers
  1643. */
  1644. public function select($fieldName, $options = [], array $attributes = [])
  1645. {
  1646. $attributes += [
  1647. 'disabled' => null,
  1648. 'escape' => true,
  1649. 'hiddenField' => true,
  1650. 'multiple' => null,
  1651. 'secure' => true,
  1652. 'empty' => false,
  1653. ];
  1654. if ($attributes['multiple'] === 'checkbox') {
  1655. unset($attributes['multiple'], $attributes['empty']);
  1656. return $this->multiCheckbox($fieldName, $options, $attributes);
  1657. }
  1658. // Secure the field if there are options, or it's a multi select.
  1659. // Single selects with no options don't submit, but multiselects do.
  1660. if ($attributes['secure'] &&
  1661. empty($options) &&
  1662. empty($attributes['empty']) &&
  1663. empty($attributes['multiple'])
  1664. ) {
  1665. $attributes['secure'] = false;
  1666. }
  1667. $attributes = $this->_initInputField($fieldName, $attributes);
  1668. $attributes['options'] = $options;
  1669. $hidden = '';
  1670. if ($attributes['multiple'] && $attributes['hiddenField']) {
  1671. $hiddenAttributes = [
  1672. 'name' => $attributes['name'],
  1673. 'value' => '',
  1674. 'form' => isset($attributes['form']) ? $attributes['form'] : null,
  1675. 'secure' => false,
  1676. ];
  1677. $hidden = $this->hidden($fieldName, $hiddenAttributes);
  1678. }
  1679. unset($attributes['hiddenField'], $attributes['type']);
  1680. return $hidden . $this->widget('select', $attributes);
  1681. }
  1682. /**
  1683. * Creates a set of checkboxes out of options.
  1684. *
  1685. * ### Options
  1686. *
  1687. * - `escape` - If true contents of options will be HTML entity encoded. Defaults to true.
  1688. * - `val` The selected value of the input.
  1689. * - `class` - When using multiple = checkbox the class name to apply to the divs. Defaults to 'checkbox'.
  1690. * - `disabled` - Control the disabled attribute. When creating checkboxes, `true` will disable all checkboxes.
  1691. * You can also set disabled to a list of values you want to disable when creating checkboxes.
  1692. * - `hiddenField` - Set to false to remove the hidden field that ensures a value
  1693. * is always submitted.
  1694. *
  1695. * Can be used in place of a select box with the multiple attribute.
  1696. *
  1697. * @param string $fieldName Name attribute of the SELECT
  1698. * @param array|\Traversable $options Array of the OPTION elements
  1699. * (as 'value'=>'Text' pairs) to be used in the checkboxes element.
  1700. * @param array $attributes The HTML attributes of the select element.
  1701. * @return string Formatted SELECT element
  1702. * @see \Cake\View\Helper\FormHelper::select() for supported option formats.
  1703. */
  1704. public function multiCheckbox($fieldName, $options, array $attributes = [])
  1705. {
  1706. $attributes += [
  1707. 'disabled' => null,
  1708. 'escape' => true,
  1709. 'hiddenField' => true,
  1710. 'secure' => true,
  1711. ];
  1712. $attributes = $this->_initInputField($fieldName, $attributes);
  1713. $attributes['options'] = $options;
  1714. $attributes['idPrefix'] = $this->_idPrefix;
  1715. $hidden = '';
  1716. if ($attributes['hiddenField']) {
  1717. $hiddenAttributes = [
  1718. 'name' => $attributes['name'],
  1719. 'value' => '',
  1720. 'secure' => false,
  1721. 'disabled' => ($attributes['disabled'] === true || $attributes['disabled'] === 'disabled'),
  1722. ];
  1723. $hidden = $this->hidden($fieldName, $hiddenAttributes);
  1724. }
  1725. return $hidden . $this->widget('multicheckbox', $attributes);
  1726. }
  1727. /**
  1728. * Helper method for the various single datetime component methods.
  1729. *
  1730. * @param array $options The options array.
  1731. * @param string $keep The option to not disable.
  1732. * @return array
  1733. */
  1734. protected function _singleDatetime($options, $keep)
  1735. {
  1736. $off = array_diff($this->_datetimeParts, [$keep]);
  1737. $off = array_combine(
  1738. $off,
  1739. array_fill(0, count($off), false)
  1740. );
  1741. $attributes = array_diff_key(
  1742. $options,
  1743. array_flip(array_merge($this->_datetimeOptions, ['value', 'empty']))
  1744. );
  1745. $options = $options + $off + [$keep => $attributes];
  1746. if (isset($options['value'])) {
  1747. $options['val'] = $options['value'];
  1748. }
  1749. return $options;
  1750. }
  1751. /**
  1752. * Returns a SELECT element for days.
  1753. *
  1754. * ### Options:
  1755. *
  1756. * - `empty` - If true, the empty select option is shown. If a string,
  1757. * that string is displayed as the empty element.
  1758. * - `value` The selected value of the input.
  1759. *
  1760. * @param string $fieldName Prefix name for the SELECT element
  1761. * @param array $options Options & HTML attributes for the select element
  1762. * @return string A generated day select box.
  1763. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-day-inputs
  1764. */
  1765. public function day($fieldName = null, array $options = [])
  1766. {
  1767. $options = $this->_singleDatetime($options, 'day');
  1768. if (isset($options['val']) && $options['val'] > 0 && $options['val'] <= 31) {
  1769. $options['val'] = [
  1770. 'year' => date('Y'),
  1771. 'month' => date('m'),
  1772. 'day' => (int)$options['val']
  1773. ];
  1774. }
  1775. return $this->datetime($fieldName, $options);
  1776. }
  1777. /**
  1778. * Returns a SELECT element for years
  1779. *
  1780. * ### Attributes:
  1781. *
  1782. * - `empty` - If true, the empty select option is shown. If a string,
  1783. * that string is displayed as the empty element.
  1784. * - `orderYear` - Ordering of year values in select options.
  1785. * Possible values 'asc', 'desc'. Default 'desc'
  1786. * - `value` The selected value of the input.
  1787. * - `maxYear` The max year to appear in the select element.
  1788. * - `minYear` The min year to appear in the select element.
  1789. *
  1790. * @param string $fieldName Prefix name for the SELECT element
  1791. * @param array $options Options & attributes for the select elements.
  1792. * @return string Completed year select input
  1793. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-year-inputs
  1794. */
  1795. public function year($fieldName, array $options = [])
  1796. {
  1797. $options = $this->_singleDatetime($options, 'year');
  1798. $len = isset($options['val']) ? strlen($options['val']) : 0;
  1799. if (isset($options['val']) && $len > 0 && $len < 5) {
  1800. $options['val'] = [
  1801. 'year' => (int)$options['val'],
  1802. 'month' => date('m'),
  1803. 'day' => date('d')
  1804. ];
  1805. }
  1806. return $this->datetime($fieldName, $options);
  1807. }
  1808. /**
  1809. * Returns a SELECT element for months.
  1810. *
  1811. * ### Options:
  1812. *
  1813. * - `monthNames` - If false, 2 digit numbers will be used instead of text.
  1814. * If an array, the given array will be used.
  1815. * - `empty` - If true, the empty select option is shown. If a string,
  1816. * that string is displayed as the empty element.
  1817. * - `value` The selected value of the input.
  1818. *
  1819. * @param string $fieldName Prefix name for the SELECT element
  1820. * @param array $options Attributes for the select element
  1821. * @return string A generated month select dropdown.
  1822. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-month-inputs
  1823. */
  1824. public function month($fieldName, array $options = [])
  1825. {
  1826. $options = $this->_singleDatetime($options, 'month');
  1827. if (isset($options['val']) && $options['val'] > 0 && $options['val'] <= 12) {
  1828. $options['val'] = [
  1829. 'year' => date('Y'),
  1830. 'month' => (int)$options['val'],
  1831. 'day' => date('d')
  1832. ];
  1833. }
  1834. return $this->datetime($fieldName, $options);
  1835. }
  1836. /**
  1837. * Returns a SELECT element for hours.
  1838. *
  1839. * ### Attributes:
  1840. *
  1841. * - `empty` - If true, the empty select option is shown. If a string,
  1842. * that string is displayed as the empty element.
  1843. * - `value` The selected value of the input.
  1844. * - `format` Set to 12 or 24 to use 12 or 24 hour formatting. Defaults to 24.
  1845. *
  1846. * @param string $fieldName Prefix name for the SELECT element
  1847. * @param array $options List of HTML attributes
  1848. * @return string Completed hour select input
  1849. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-hour-inputs
  1850. */
  1851. public function hour($fieldName, array $options = [])
  1852. {
  1853. $options += ['format' => 24];
  1854. $options = $this->_singleDatetime($options, 'hour');
  1855. $options['timeFormat'] = $options['format'];
  1856. unset($options['format']);
  1857. if (isset($options['val']) && $options['val'] > 0 && $options['val'] <= 24) {
  1858. $options['val'] = [
  1859. 'hour' => (int)$options['val'],
  1860. 'minute' => date('i'),
  1861. ];
  1862. }
  1863. return $this->datetime($fieldName, $options);
  1864. }
  1865. /**
  1866. * Returns a SELECT element for minutes.
  1867. *
  1868. * ### Attributes:
  1869. *
  1870. * - `empty` - If true, the empty select option is shown. If a string,
  1871. * that string is displayed as the empty element.
  1872. * - `value` The selected value of the input.
  1873. * - `interval` The interval that minute options should be created at.
  1874. * - `round` How you want the value rounded when it does not fit neatly into an
  1875. * interval. Accepts 'up', 'down', and null.
  1876. *
  1877. * @param string $fieldName Prefix name for the SELECT element
  1878. * @param array $options Array of options.
  1879. * @return string Completed minute select input.
  1880. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-minute-inputs
  1881. */
  1882. public function minute($fieldName, array $options = [])
  1883. {
  1884. $options = $this->_singleDatetime($options, 'minute');
  1885. if (isset($options['val']) && $options['val'] > 0 && $options['val'] <= 60) {
  1886. $options['val'] = [
  1887. 'hour' => date('H'),
  1888. 'minute' => (int)$options['val'],
  1889. ];
  1890. }
  1891. return $this->datetime($fieldName, $options);
  1892. }
  1893. /**
  1894. * Returns a SELECT element for AM or PM.
  1895. *
  1896. * ### Attributes:
  1897. *
  1898. * - `empty` - If true, the empty select option is shown. If a string,
  1899. * that string is displayed as the empty element.
  1900. * - `value` The selected value of the input.
  1901. *
  1902. * @param string $fieldName Prefix name for the SELECT element
  1903. * @param array $options Array of options
  1904. * @return string Completed meridian select input
  1905. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-meridian-inputs
  1906. */
  1907. public function meridian($fieldName, array $options = [])
  1908. {
  1909. $options = $this->_singleDatetime($options, 'meridian');
  1910. if (isset($options['val'])) {
  1911. $hour = date('H');
  1912. $options['val'] = [
  1913. 'hour' => $hour,
  1914. 'minute' => (int)$options['val'],
  1915. 'meridian' => $hour > 11 ? 'pm' : 'am',
  1916. ];
  1917. }
  1918. return $this->datetime($fieldName, $options);
  1919. }
  1920. /**
  1921. * Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
  1922. *
  1923. * ### Date Options:
  1924. *
  1925. * - `empty` - If true, the empty select option is shown. If a string,
  1926. * that string is displayed as the empty element.
  1927. * - `value` | `default` The default value to be used by the input. A value in `$this->data`
  1928. * matching the field name will override this value. If no default is provided `time()` will be used.
  1929. * - `monthNames` If false, 2 digit numbers will be used instead of text.
  1930. * If an array, the given array will be used.
  1931. * - `minYear` The lowest year to use in the year select
  1932. * - `maxYear` The maximum year to use in the year select
  1933. * - `orderYear` - Order of year values in select options.
  1934. * Possible values 'asc', 'desc'. Default 'desc'.
  1935. *
  1936. * ### Time options:
  1937. *
  1938. * - `empty` - If true, the empty select option is shown. If a string,
  1939. * - `value` | `default` The default value to be used by the input. A value in `$this->data`
  1940. * matching the field name will override this value. If no default is provided `time()` will be used.
  1941. * - `timeFormat` The time format to use, either 12 or 24.
  1942. * - `interval` The interval for the minutes select. Defaults to 1
  1943. * - `round` - Set to `up` or `down` if you want to force rounding in either direction. Defaults to null.
  1944. * - `second` Set to true to enable seconds drop down.
  1945. *
  1946. * To control the order of inputs, and any elements/content between the inputs you
  1947. * can override the `dateWidget` template. By default the `dateWidget` template is:
  1948. *
  1949. * `{{month}}{{day}}{{year}}{{hour}}{{minute}}{{second}}{{meridian}}`
  1950. *
  1951. * @param string $fieldName Prefix name for the SELECT element
  1952. * @param array $options Array of Options
  1953. * @return string Generated set of select boxes for the date and time formats chosen.
  1954. * @link http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-date-and-time-inputs
  1955. */
  1956. public function dateTime($fieldName, array $options = [])
  1957. {
  1958. $options += [
  1959. 'empty' => true,
  1960. 'value' => null,
  1961. 'interval' => 1,
  1962. 'round' => null,
  1963. 'monthNames' => true,
  1964. 'minYear' => null,
  1965. 'maxYear' => null,
  1966. 'orderYear' => 'desc',
  1967. 'timeFormat' => 24,
  1968. 'second' => false,
  1969. ];
  1970. $options = $this->_initInputField($fieldName, $options);
  1971. $options = $this->_datetimeOptions($options);
  1972. return $this->widget('datetime', $options);
  1973. }
  1974. /**
  1975. * Helper method for converting from FormHelper options data to widget format.
  1976. *
  1977. * @param array $options Options to convert.
  1978. * @return array Converted options.
  1979. */
  1980. protected function _datetimeOptions($options)
  1981. {
  1982. foreach ($this->_datetimeParts as $type) {
  1983. if (!isset($options[$type])) {
  1984. $options[$type] = [];
  1985. }
  1986. // Pass empty options to each type.
  1987. if (!empty($options['empty']) &&
  1988. is_array($options[$type])
  1989. ) {
  1990. $options[$type]['empty'] = $options['empty'];
  1991. }
  1992. // Move empty options into each type array.
  1993. if (isset($options['empty'][$type])) {
  1994. $options[$type]['empty'] = $options['empty'][$type];
  1995. }
  1996. }
  1997. unset($options['empty']);
  1998. $hasYear = is_array($options['year']);
  1999. if ($hasYear && isset($options['minYear'])) {
  2000. $options['year']['start'] = $options['minYear'];
  2001. }
  2002. if ($hasYear && isset($options['maxYear'])) {
  2003. $options['year']['end'] = $options['maxYear'];
  2004. }
  2005. if ($hasYear && isset($options['orderYear'])) {
  2006. $options['year']['order'] = $options['orderYear'];
  2007. }
  2008. unset($options['minYear'], $options['maxYear'], $options['orderYear']);
  2009. if (is_array($options['month'])) {
  2010. $options['month']['names'] = $options['monthNames'];
  2011. }
  2012. unset($options['monthNames']);
  2013. if (is_array($options['hour']) && isset($options['timeFormat'])) {
  2014. $options['hour']['format'] = $options['timeFormat'];
  2015. }
  2016. unset($options['timeFormat']);
  2017. if (is_array($options['minute'])) {
  2018. $options['minute']['interval'] = $options['interval'];
  2019. $options['minute']['round'] = $options['round'];
  2020. }
  2021. unset($options['interval'], $options['round']);
  2022. if (!isset($options['val'])) {
  2023. $val = new \DateTime();
  2024. $currentYear = $val->format('Y');
  2025. if (isset($options['year']['end']) && $options['year']['end'] < $currentYear) {
  2026. $val->setDate($options['year']['end'], $val->format('n'), $val->format('j'));
  2027. }
  2028. $options['val'] = $val;
  2029. }
  2030. return $options;
  2031. }
  2032. /**
  2033. * Generate time inputs.
  2034. *
  2035. * ### Options:
  2036. *
  2037. * See dateTime() for time options.
  2038. *
  2039. * @param string $fieldName Prefix name for the SELECT element
  2040. * @param array $options Array of Options
  2041. * @return string Generated set of select boxes for time formats chosen.
  2042. * @see Cake\View\Helper\FormHelper::dateTime() for templating options.
  2043. */
  2044. public function time($fieldName, array $options = [])
  2045. {
  2046. $options += [
  2047. 'empty' => true,
  2048. 'value' => null,
  2049. 'interval' => 1,
  2050. 'round' => null,
  2051. 'timeFormat' => 24,
  2052. 'second' => false,
  2053. ];
  2054. $options['year'] = $options['month'] = $options['day'] = false;
  2055. $options = $this->_initInputField($fieldName, $options);
  2056. $options = $this->_datetimeOptions($options);
  2057. return $this->widget('datetime', $options);
  2058. }
  2059. /**
  2060. * Generate date inputs.
  2061. *
  2062. * ### Options:
  2063. *
  2064. * See dateTime() for date options.
  2065. *
  2066. * @param string $fieldName Prefix name for the SELECT element
  2067. * @param array $options Array of Options
  2068. * @return string Generated set of select boxes for time formats chosen.
  2069. * @see Cake\View\Helper\FormHelper::dateTime() for templating options.
  2070. */
  2071. public function date($fieldName, array $options = [])
  2072. {
  2073. $options += [
  2074. 'empty' => true,
  2075. 'value' => null,
  2076. 'monthNames' => true,
  2077. 'minYear' => null,
  2078. 'maxYear' => null,
  2079. 'orderYear' => 'desc',
  2080. ];
  2081. $options['hour'] = $options['minute'] = false;
  2082. $options['meridian'] = $options['second'] = false;
  2083. $options = $this->_initInputField($fieldName, $options);
  2084. $options = $this->_datetimeOptions($options);
  2085. return $this->widget('datetime', $options);
  2086. }
  2087. /**
  2088. * Sets field defaults and adds field to form security input hash.
  2089. * Will also add the error class if the field contains validation errors.
  2090. *
  2091. * ### Options
  2092. *
  2093. * - `secure` - boolean whether or not the field should be added to the security fields.
  2094. * Disabling the field using the `disabled` option, will also omit the field from being
  2095. * part of the hashed key.
  2096. * - `default` - mixed - The value to use if there is no value in the form's context.
  2097. * - `disabled` - mixed - Either a boolean indicating disabled state, or the string in
  2098. * a numerically indexed value.
  2099. *
  2100. * This method will convert a numerically indexed 'disabled' into an associative
  2101. * array value. FormHelper's internals expect associative options.
  2102. *
  2103. * The output of this function is a more complete set of input attributes that
  2104. * can be passed to a form widget to generate the actual input.
  2105. *
  2106. * @param string $field Name of the field to initialize options for.
  2107. * @param array $options Array of options to append options into.
  2108. * @return array Array of options for the input.
  2109. */
  2110. protected function _initInputField($field, $options = [])
  2111. {
  2112. if (!isset($options['secure'])) {
  2113. $options['secure'] = !empty($this->request->params['_Token']);
  2114. }
  2115. $context = $this->_getContext();
  2116. $disabledIndex = array_search('disabled', $options, true);
  2117. if (is_int($disabledIndex)) {
  2118. unset($options[$disabledIndex]);
  2119. $options['disabled'] = true;
  2120. }
  2121. if (!isset($options['name'])) {
  2122. $parts = explode('.', $field);
  2123. $first = array_shift($parts);
  2124. $options['name'] = $first . ($parts ? '[' . implode('][', $parts) . ']' : '');
  2125. }
  2126. if (isset($options['value']) && !isset($options['val'])) {
  2127. $options['val'] = $options['value'];
  2128. unset($options['value']);
  2129. }
  2130. if (!isset($options['val'])) {
  2131. $options['val'] = $context->val($field);
  2132. }
  2133. if (!isset($options['val']) && isset($options['default'])) {
  2134. $options['val'] = $options['default'];
  2135. }
  2136. unset($options['value'], $options['default']);
  2137. if ($context->hasError($field)) {
  2138. $options = $this->addClass($options, $this->_config['errorClass']);
  2139. }
  2140. $isDisabled = false;
  2141. if (isset($options['disabled'])) {
  2142. $isDisabled = (
  2143. $options['disabled'] === true ||
  2144. $options['disabled'] === 'disabled' ||
  2145. (is_array($options['disabled']) &&
  2146. !empty($options['options']) &&
  2147. array_diff($options['options'], $options['disabled']) === array()
  2148. )
  2149. );
  2150. }
  2151. if ($isDisabled) {
  2152. $options['secure'] = self::SECURE_SKIP;
  2153. }
  2154. if ($options['secure'] === self::SECURE_SKIP) {
  2155. return $options;
  2156. }
  2157. if (!isset($options['required']) && empty($options['disabled']) && $context->isRequired($field)) {
  2158. $options['required'] = true;
  2159. }
  2160. return $options;
  2161. }
  2162. /**
  2163. * Get the field name for use with _secure().
  2164. *
  2165. * Parses the name attribute to create a dot separated name value for use
  2166. * in secured field hash. If filename is of form Model[field] an array of
  2167. * fieldname parts like ['Model', 'field'] is returned.
  2168. *
  2169. * @param string $name The form inputs name attribute.
  2170. * @return string|array|null Dot separated string like Foo.bar, array of filename
  2171. * params like ['Model', 'field'] or null if options does not contain name.
  2172. */
  2173. protected function _secureFieldName($name)
  2174. {
  2175. if (strpos($name, '[') === false) {
  2176. return [$name];
  2177. }
  2178. $parts = explode('[', $name);
  2179. $parts = array_map(function ($el) {
  2180. return trim($el, ']');
  2181. }, $parts);
  2182. return $parts;
  2183. }
  2184. /**
  2185. * Add a new context type.
  2186. *
  2187. * Form context types allow FormHelper to interact with
  2188. * data providers that come from outside CakePHP. For example
  2189. * if you wanted to use an alternative ORM like Doctrine you could
  2190. * create and connect a new context class to allow FormHelper to
  2191. * read metadata from doctrine.
  2192. *
  2193. * @param string $type The type of context. This key
  2194. * can be used to overwrite existing providers.
  2195. * @param callable $check A callable that returns an object
  2196. * when the form context is the correct type.
  2197. * @return void
  2198. */
  2199. public function addContextProvider($type, callable $check)
  2200. {
  2201. foreach ($this->_contextProviders as $i => $provider) {
  2202. if ($provider['type'] === $type) {
  2203. unset($this->_contextProviders[$i]);
  2204. }
  2205. }
  2206. array_unshift($this->_contextProviders, ['type' => $type, 'callable' => $check]);
  2207. }
  2208. /**
  2209. * Get the context instance for the current form set.
  2210. *
  2211. * If there is no active form null will be returned.
  2212. *
  2213. * @param \Cake\View\Form\ContextInterface|null $context Either the new context when setting, or null to get.
  2214. * @return null|\Cake\View\Form\ContextInterface The context for the form.
  2215. */
  2216. public function context($context = null)
  2217. {
  2218. if ($context instanceof ContextInterface) {
  2219. $this->_context = $context;
  2220. }
  2221. return $this->_getContext();
  2222. }
  2223. /**
  2224. * Find the matching context provider for the data.
  2225. *
  2226. * If no type can be matched a NullContext will be returned.
  2227. *
  2228. * @param mixed $data The data to get a context provider for.
  2229. * @return mixed Context provider.
  2230. * @throws \RuntimeException when the context class does not implement the
  2231. * ContextInterface.
  2232. */
  2233. protected function _getContext($data = [])
  2234. {
  2235. if (isset($this->_context) && empty($data)) {
  2236. return $this->_context;
  2237. }
  2238. $data += ['entity' => null];
  2239. foreach ($this->_contextProviders as $provider) {
  2240. $check = $provider['callable'];
  2241. $context = $check($this->request, $data);
  2242. if ($context) {
  2243. break;
  2244. }
  2245. }
  2246. if (!isset($context)) {
  2247. $context = new NullContext($this->request, $data);
  2248. }
  2249. if (!($context instanceof ContextInterface)) {
  2250. throw new \RuntimeException(
  2251. 'Context objects must implement Cake\View\Form\ContextInterface'
  2252. );
  2253. }
  2254. return $this->_context = $context;
  2255. }
  2256. /**
  2257. * Add a new widget to FormHelper.
  2258. *
  2259. * Allows you to add or replace widget instances with custom code.
  2260. *
  2261. * @param string $name The name of the widget. e.g. 'text'.
  2262. * @param array|\Cake\View\Widget\WidgetInterface $spec Either a string class
  2263. * name or an object implementing the WidgetInterface.
  2264. * @return void
  2265. */
  2266. public function addWidget($name, $spec)
  2267. {
  2268. $this->_registry->add([$name => $spec]);
  2269. }
  2270. /**
  2271. * Render a named widget.
  2272. *
  2273. * This is a lower level method. For built-in widgets, you should be using
  2274. * methods like `text`, `hidden`, and `radio`. If you are using additional
  2275. * widgets you should use this method render the widget without the label
  2276. * or wrapping div.
  2277. *
  2278. * @param string $name The name of the widget. e.g. 'text'.
  2279. * @param array $data The data to render.
  2280. * @return string
  2281. */
  2282. public function widget($name, array $data = [])
  2283. {
  2284. $widget = $this->_registry->get($name);
  2285. if (isset($data['secure'], $data['name']) &&
  2286. $data['secure'] !== self::SECURE_SKIP
  2287. ) {
  2288. foreach ($widget->secureFields($data) as $field) {
  2289. $this->_secure($data['secure'], $this->_secureFieldName($field));
  2290. }
  2291. }
  2292. unset($data['secure']);
  2293. return $widget->render($data, $this->context());
  2294. }
  2295. /**
  2296. * Restores the default values built into FormHelper.
  2297. *
  2298. * This method will not reset any templates set in custom widgets.
  2299. *
  2300. * @return void
  2301. */
  2302. public function resetTemplates()
  2303. {
  2304. $this->templates($this->_defaultConfig['templates']);
  2305. }
  2306. /**
  2307. * Event listeners.
  2308. *
  2309. * @return array
  2310. */
  2311. public function implementedEvents()
  2312. {
  2313. return [];
  2314. }
  2315. }