FormHelper.php 91 KB

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