FormHelper.php 92 KB

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