FormHelper.php 89 KB

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