FormHelper.php 107 KB

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