FormHelper.php 90 KB

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