FormHelper.php 105 KB

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