FormHelper.php 92 KB

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