FormHelper.php 107 KB

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