FormHelper.php 89 KB

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