PageRenderTime 49ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/src/View/Helper/FormHelper.php

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