FormHelper.php 92 KB

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