FormHelper.php 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 0.10.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\View\Helper;
  16. use Cake\Core\Configure;
  17. use Cake\Core\Exception\Exception;
  18. use Cake\Routing\Router;
  19. use Cake\Utility\Hash;
  20. use Cake\Utility\Inflector;
  21. use Cake\View\Form\ContextFactory;
  22. use Cake\View\Form\ContextInterface;
  23. use Cake\View\Helper;
  24. use Cake\View\StringTemplateTrait;
  25. use Cake\View\View;
  26. use Cake\View\Widget\WidgetLocator;
  27. use Cake\View\Widget\WidgetRegistry;
  28. use DateTime;
  29. use RuntimeException;
  30. use Traversable;
  31. /**
  32. * Form helper library.
  33. *
  34. * Automatic generation of HTML FORMs from given data.
  35. *
  36. * @method string text($fieldName, array $options = [])
  37. * @method string number($fieldName, array $options = [])
  38. * @method string email($fieldName, array $options = [])
  39. * @method string password($fieldName, array $options = [])
  40. * @method string search($fieldName, array $options = [])
  41. *
  42. * @property \Cake\View\Helper\HtmlHelper $Html
  43. * @property \Cake\View\Helper\UrlHelper $Url
  44. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html
  45. */
  46. class FormHelper extends Helper
  47. {
  48. use IdGeneratorTrait;
  49. use SecureFieldTokenTrait;
  50. use StringTemplateTrait;
  51. /**
  52. * Other helpers used by FormHelper
  53. *
  54. * @var array
  55. */
  56. public $helpers = ['Url', 'Html'];
  57. /**
  58. * The various pickers that make up a datetime picker.
  59. *
  60. * @var array
  61. */
  62. protected $_datetimeParts = ['year', 'month', 'day', 'hour', 'minute', 'second', 'meridian'];
  63. /**
  64. * Special options used for datetime inputs.
  65. *
  66. * @var array
  67. */
  68. protected $_datetimeOptions = [
  69. 'interval', 'round', 'monthNames', 'minYear', 'maxYear',
  70. 'orderYear', 'timeFormat', 'second'
  71. ];
  72. /**
  73. * Default config for the helper.
  74. *
  75. * @var array
  76. */
  77. protected $_defaultConfig = [
  78. 'idPrefix' => null,
  79. 'errorClass' => 'form-error',
  80. 'typeMap' => [
  81. 'string' => 'text',
  82. 'text' => 'textarea',
  83. 'uuid' => 'string',
  84. 'datetime' => 'datetime',
  85. 'timestamp' => 'datetime',
  86. 'date' => 'date',
  87. 'time' => 'time',
  88. 'boolean' => 'checkbox',
  89. 'float' => 'number',
  90. 'integer' => 'number',
  91. 'tinyinteger' => 'number',
  92. 'smallinteger' => 'number',
  93. 'decimal' => 'number',
  94. 'binary' => 'file',
  95. ],
  96. 'templates' => [
  97. // Used for button elements in button().
  98. 'button' => '<button{{attrs}}>{{text}}</button>',
  99. // Used for checkboxes in checkbox() and multiCheckbox().
  100. 'checkbox' => '<input type="checkbox" name="{{name}}" value="{{value}}"{{attrs}}>',
  101. // Input group wrapper for checkboxes created via control().
  102. 'checkboxFormGroup' => '{{label}}',
  103. // Wrapper container for checkboxes.
  104. 'checkboxWrapper' => '<div class="checkbox">{{label}}</div>',
  105. // Widget ordering for date/time/datetime pickers.
  106. 'dateWidget' => '{{year}}{{month}}{{day}}{{hour}}{{minute}}{{second}}{{meridian}}',
  107. // Error message wrapper elements.
  108. 'error' => '<div class="error-message">{{content}}</div>',
  109. // Container for error items.
  110. 'errorList' => '<ul>{{content}}</ul>',
  111. // Error item wrapper.
  112. 'errorItem' => '<li>{{text}}</li>',
  113. // File input used by file().
  114. 'file' => '<input type="file" name="{{name}}"{{attrs}}>',
  115. // Fieldset element used by allControls().
  116. 'fieldset' => '<fieldset{{attrs}}>{{content}}</fieldset>',
  117. // Open tag used by create().
  118. 'formStart' => '<form{{attrs}}>',
  119. // Close tag used by end().
  120. 'formEnd' => '</form>',
  121. // General grouping container for control(). Defines input/label ordering.
  122. 'formGroup' => '{{label}}{{input}}',
  123. // Wrapper content used to hide other content.
  124. 'hiddenBlock' => '<div style="display:none;">{{content}}</div>',
  125. // Generic input element.
  126. 'input' => '<input type="{{type}}" name="{{name}}"{{attrs}}/>',
  127. // Submit input element.
  128. 'inputSubmit' => '<input type="{{type}}"{{attrs}}/>',
  129. // Container element used by control().
  130. 'inputContainer' => '<div class="input {{type}}{{required}}">{{content}}</div>',
  131. // Container element used by control() when a field has an error.
  132. 'inputContainerError' => '<div class="input {{type}}{{required}} error">{{content}}{{error}}</div>',
  133. // Label element when inputs are not nested inside the label.
  134. 'label' => '<label{{attrs}}>{{text}}</label>',
  135. // Label element used for radio and multi-checkbox inputs.
  136. 'nestingLabel' => '{{hidden}}<label{{attrs}}>{{input}}{{text}}</label>',
  137. // Legends created by allControls()
  138. 'legend' => '<legend>{{text}}</legend>',
  139. // Multi-Checkbox input set title element.
  140. 'multicheckboxTitle' => '<legend>{{text}}</legend>',
  141. // Multi-Checkbox wrapping container.
  142. 'multicheckboxWrapper' => '<fieldset{{attrs}}>{{content}}</fieldset>',
  143. // Option element used in select pickers.
  144. 'option' => '<option value="{{value}}"{{attrs}}>{{text}}</option>',
  145. // Option group element used in select pickers.
  146. 'optgroup' => '<optgroup label="{{label}}"{{attrs}}>{{content}}</optgroup>',
  147. // Select element,
  148. 'select' => '<select name="{{name}}"{{attrs}}>{{content}}</select>',
  149. // Multi-select element,
  150. 'selectMultiple' => '<select name="{{name}}[]" multiple="multiple"{{attrs}}>{{content}}</select>',
  151. // Radio input element,
  152. 'radio' => '<input type="radio" name="{{name}}" value="{{value}}"{{attrs}}>',
  153. // Wrapping container for radio input/label,
  154. 'radioWrapper' => '{{label}}',
  155. // Textarea input element,
  156. 'textarea' => '<textarea name="{{name}}"{{attrs}}>{{value}}</textarea>',
  157. // Container for submit buttons.
  158. 'submitContainer' => '<div class="submit">{{content}}</div>',
  159. //Confirm javascript template for postLink()
  160. 'confirmJs' => '{{confirm}}',
  161. ],
  162. // set HTML5 validation message to custom required/empty messages
  163. 'autoSetCustomValidity' => false,
  164. ];
  165. /**
  166. * Default widgets
  167. *
  168. * @var array
  169. */
  170. protected $_defaultWidgets = [
  171. 'button' => ['Button'],
  172. 'checkbox' => ['Checkbox'],
  173. 'file' => ['File'],
  174. 'label' => ['Label'],
  175. 'nestingLabel' => ['NestingLabel'],
  176. 'multicheckbox' => ['MultiCheckbox', 'nestingLabel'],
  177. 'radio' => ['Radio', 'nestingLabel'],
  178. 'select' => ['SelectBox'],
  179. 'textarea' => ['Textarea'],
  180. 'datetime' => ['DateTime', 'select'],
  181. '_default' => ['Basic'],
  182. ];
  183. /**
  184. * List of fields created, used with secure forms.
  185. *
  186. * @var array
  187. */
  188. public $fields = [];
  189. /**
  190. * Constant used internally to skip the securing process,
  191. * and neither add the field to the hash or to the unlocked fields.
  192. *
  193. * @var string
  194. */
  195. const SECURE_SKIP = 'skip';
  196. /**
  197. * Defines the type of form being created. Set by FormHelper::create().
  198. *
  199. * @var string|null
  200. */
  201. public $requestType;
  202. /**
  203. * An array of field names that have been excluded from
  204. * the Token hash used by SecurityComponent's validatePost method
  205. *
  206. * @see \Cake\View\Helper\FormHelper::_secure()
  207. * @see \Cake\Controller\Component\SecurityComponent::validatePost()
  208. * @var string[]
  209. */
  210. protected $_unlockedFields = [];
  211. /**
  212. * Locator for input widgets.
  213. *
  214. * @var \Cake\View\Widget\WidgetLocator
  215. */
  216. protected $_locator;
  217. /**
  218. * Context for the current form.
  219. *
  220. * @var \Cake\View\Form\ContextInterface|null
  221. */
  222. protected $_context;
  223. /**
  224. * Context factory.
  225. *
  226. * @var \Cake\View\Form\ContextFactory
  227. */
  228. protected $_contextFactory;
  229. /**
  230. * The action attribute value of the last created form.
  231. * Used to make form/request specific hashes for SecurityComponent.
  232. *
  233. * @var string
  234. */
  235. protected $_lastAction = '';
  236. /**
  237. * The sources to be used when retrieving prefilled input values.
  238. *
  239. * @var string[]
  240. */
  241. protected $_valueSources = ['context'];
  242. /**
  243. * Grouped input types.
  244. *
  245. * @var string[]
  246. */
  247. protected $_groupedInputTypes = ['radio', 'multicheckbox', 'date', 'time', 'datetime'];
  248. /**
  249. * Construct the widgets and binds the default context providers
  250. *
  251. * @param \Cake\View\View $View The View this helper is being attached to.
  252. * @param array $config Configuration settings for the helper.
  253. */
  254. public function __construct(View $View, array $config = [])
  255. {
  256. $locator = null;
  257. $widgets = $this->_defaultWidgets;
  258. if (isset($config['registry'])) {
  259. deprecationWarning('`registry` config key is deprecated in FormHelper, use `locator` instead.');
  260. $config['locator'] = $config['registry'];
  261. unset($config['registry']);
  262. }
  263. if (isset($config['locator'])) {
  264. $locator = $config['locator'];
  265. unset($config['locator']);
  266. }
  267. if (isset($config['widgets'])) {
  268. if (is_string($config['widgets'])) {
  269. $config['widgets'] = (array)$config['widgets'];
  270. }
  271. $widgets = $config['widgets'] + $widgets;
  272. unset($config['widgets']);
  273. }
  274. if (isset($config['groupedInputTypes'])) {
  275. $this->_groupedInputTypes = $config['groupedInputTypes'];
  276. unset($config['groupedInputTypes']);
  277. }
  278. parent::__construct($View, $config);
  279. if (!$locator) {
  280. $locator = new WidgetLocator($this->templater(), $this->_View, $widgets);
  281. }
  282. $this->setWidgetLocator($locator);
  283. $this->_idPrefix = $this->getConfig('idPrefix');
  284. }
  285. /**
  286. * Set the widget registry the helper will use.
  287. *
  288. * @param \Cake\View\Widget\WidgetRegistry|null $instance The registry instance to set.
  289. * @param array $widgets An array of widgets
  290. * @return \Cake\View\Widget\WidgetRegistry
  291. * @deprecated 3.6.0 Use FormHelper::widgetLocator() instead.
  292. */
  293. public function widgetRegistry(WidgetRegistry $instance = null, $widgets = [])
  294. {
  295. deprecationWarning('widgetRegistry is deprecated, use widgetLocator instead.');
  296. if ($instance) {
  297. $instance->add($widgets);
  298. $this->setWidgetLocator($instance);
  299. }
  300. return $this->getWidgetLocator();
  301. }
  302. /**
  303. * Get the widget locator currently used by the helper.
  304. *
  305. * @return \Cake\View\Widget\WidgetLocator Current locator instance
  306. * @since 3.6.0
  307. */
  308. public function getWidgetLocator()
  309. {
  310. return $this->_locator;
  311. }
  312. /**
  313. * Set the widget locator the helper will use.
  314. *
  315. * @param \Cake\View\Widget\WidgetLocator $instance The locator instance to set.
  316. * @return $this
  317. * @since 3.6.0
  318. */
  319. public function setWidgetLocator(WidgetLocator $instance)
  320. {
  321. $this->_locator = $instance;
  322. return $this;
  323. }
  324. /**
  325. * Set the context factory the helper will use.
  326. *
  327. * @param \Cake\View\Form\ContextFactory|null $instance The context factory instance to set.
  328. * @param array $contexts An array of context providers.
  329. * @return \Cake\View\Form\ContextFactory
  330. */
  331. public function contextFactory(ContextFactory $instance = null, array $contexts = [])
  332. {
  333. if ($instance === null) {
  334. if ($this->_contextFactory === null) {
  335. $this->_contextFactory = ContextFactory::createWithDefaults($contexts);
  336. }
  337. return $this->_contextFactory;
  338. }
  339. $this->_contextFactory = $instance;
  340. return $this->_contextFactory;
  341. }
  342. /**
  343. * Returns an HTML form element.
  344. *
  345. * ### Options:
  346. *
  347. * - `type` Form method defaults to autodetecting based on the form context. If
  348. * the form context's isCreate() method returns false, a PUT request will be done.
  349. * - `method` Set the form's method attribute explicitly.
  350. * - `action` The controller action the form submits to, (optional). Use this option if you
  351. * don't need to change the controller from the current request's controller. Deprecated since 3.2, use `url`.
  352. * - `url` The URL the form submits to. Can be a string or a URL array. If you use 'url'
  353. * you should leave 'action' undefined.
  354. * - `encoding` Set the accept-charset encoding for the form. Defaults to `Configure::read('App.encoding')`
  355. * - `enctype` Set the form encoding explicitly. By default `type => file` will set `enctype`
  356. * to `multipart/form-data`.
  357. * - `templates` The templates you want to use for this form. Any templates will be merged on top of
  358. * the already loaded templates. This option can either be a filename in /config that contains
  359. * the templates you want to load, or an array of templates to use.
  360. * - `context` Additional options for the context class. For example the EntityContext accepts a 'table'
  361. * option that allows you to set the specific Table class the form should be based on.
  362. * - `idPrefix` Prefix for generated ID attributes.
  363. * - `valueSources` The sources that values should be read from. See FormHelper::setValueSources()
  364. * - `templateVars` Provide template variables for the formStart template.
  365. *
  366. * @param mixed $context The context for which the form is being defined.
  367. * Can be a ContextInterface instance, ORM entity, ORM resultset, or an
  368. * array of meta data. You can use false or null to make a context-less form.
  369. * @param array $options An array of html attributes and options.
  370. * @return string An formatted opening FORM tag.
  371. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#Cake\View\Helper\FormHelper::create
  372. */
  373. public function create($context = null, array $options = [])
  374. {
  375. $append = '';
  376. if ($context instanceof ContextInterface) {
  377. $this->context($context);
  378. } else {
  379. if (empty($options['context'])) {
  380. $options['context'] = [];
  381. }
  382. $options['context']['entity'] = $context;
  383. $context = $this->_getContext($options['context']);
  384. unset($options['context']);
  385. }
  386. $isCreate = $context->isCreate();
  387. $options += [
  388. 'type' => $isCreate ? 'post' : 'put',
  389. 'action' => null,
  390. 'url' => null,
  391. 'encoding' => strtolower(Configure::read('App.encoding')),
  392. 'templates' => null,
  393. 'idPrefix' => null,
  394. 'valueSources' => null,
  395. ];
  396. if (isset($options['action'])) {
  397. trigger_error('Using key `action` is deprecated, use `url` directly instead.', E_USER_DEPRECATED);
  398. }
  399. if (isset($options['valueSources'])) {
  400. $this->setValueSources($options['valueSources']);
  401. unset($options['valueSources']);
  402. }
  403. if ($options['idPrefix'] !== null) {
  404. $this->_idPrefix = $options['idPrefix'];
  405. }
  406. $templater = $this->templater();
  407. if (!empty($options['templates'])) {
  408. $templater->push();
  409. $method = is_string($options['templates']) ? 'load' : 'add';
  410. $templater->{$method}($options['templates']);
  411. }
  412. unset($options['templates']);
  413. if ($options['action'] === false || $options['url'] === false) {
  414. $url = $this->_View->getRequest()->getRequestTarget();
  415. $action = null;
  416. } else {
  417. $url = $this->_formUrl($context, $options);
  418. $action = $this->Url->build($url);
  419. }
  420. $this->_lastAction($url);
  421. unset($options['url'], $options['action'], $options['idPrefix']);
  422. $htmlAttributes = [];
  423. switch (strtolower($options['type'])) {
  424. case 'get':
  425. $htmlAttributes['method'] = 'get';
  426. break;
  427. // Set enctype for form
  428. case 'file':
  429. $htmlAttributes['enctype'] = 'multipart/form-data';
  430. $options['type'] = $isCreate ? 'post' : 'put';
  431. // Move on
  432. case 'post':
  433. // Move on
  434. case 'put':
  435. // Move on
  436. case 'delete':
  437. // Set patch method
  438. case 'patch':
  439. $append .= $this->hidden('_method', [
  440. 'name' => '_method',
  441. 'value' => strtoupper($options['type']),
  442. 'secure' => static::SECURE_SKIP
  443. ]);
  444. // Default to post method
  445. default:
  446. $htmlAttributes['method'] = 'post';
  447. }
  448. if (isset($options['method'])) {
  449. $htmlAttributes['method'] = strtolower($options['method']);
  450. }
  451. if (isset($options['enctype'])) {
  452. $htmlAttributes['enctype'] = strtolower($options['enctype']);
  453. }
  454. $this->requestType = strtolower($options['type']);
  455. if (!empty($options['encoding'])) {
  456. $htmlAttributes['accept-charset'] = $options['encoding'];
  457. }
  458. unset($options['type'], $options['encoding']);
  459. $htmlAttributes += $options;
  460. $this->fields = [];
  461. if ($this->requestType !== 'get') {
  462. $append .= $this->_csrfField();
  463. }
  464. if (!empty($append)) {
  465. $append = $templater->format('hiddenBlock', ['content' => $append]);
  466. }
  467. $actionAttr = $templater->formatAttributes(['action' => $action, 'escape' => false]);
  468. return $this->formatTemplate('formStart', [
  469. 'attrs' => $templater->formatAttributes($htmlAttributes) . $actionAttr,
  470. 'templateVars' => isset($options['templateVars']) ? $options['templateVars'] : []
  471. ]) . $append;
  472. }
  473. /**
  474. * Create the URL for a form based on the options.
  475. *
  476. * @param \Cake\View\Form\ContextInterface $context The context object to use.
  477. * @param array $options An array of options from create()
  478. * @return string|array The action attribute for the form.
  479. */
  480. protected function _formUrl($context, $options)
  481. {
  482. $request = $this->_View->getRequest();
  483. if ($options['action'] === null && $options['url'] === null) {
  484. return $request->getRequestTarget();
  485. }
  486. if (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.0/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.0/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.0/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.0/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.0/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.0/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.0/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.0/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.0/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 input().
  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.0/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.0/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 (!array_key_exists('maxlength', $options)
  1354. && in_array($options['type'], $typesWithMaxLength)
  1355. ) {
  1356. $maxLength = null;
  1357. if (method_exists($context, 'getMaxLength')) {
  1358. $maxLength = $context->getMaxLength($fieldName);
  1359. }
  1360. if ($maxLength === null && !empty($fieldDef['length'])) {
  1361. $maxLength = $fieldDef['length'];
  1362. }
  1363. if ($maxLength !== null) {
  1364. $options['maxlength'] = min($maxLength, 100000);
  1365. }
  1366. }
  1367. if (in_array($options['type'], ['datetime', 'date', 'time', 'select'])) {
  1368. $options += ['empty' => false];
  1369. }
  1370. return $options;
  1371. }
  1372. /**
  1373. * Generate label for input
  1374. *
  1375. * @param string $fieldName The name of the field to generate label for.
  1376. * @param array $options Options list.
  1377. * @return bool|string false or Generated label element
  1378. */
  1379. protected function _getLabel($fieldName, $options)
  1380. {
  1381. if ($options['type'] === 'hidden') {
  1382. return false;
  1383. }
  1384. $label = null;
  1385. if (isset($options['label'])) {
  1386. $label = $options['label'];
  1387. }
  1388. if ($label === false && $options['type'] === 'checkbox') {
  1389. return $options['input'];
  1390. }
  1391. if ($label === false) {
  1392. return false;
  1393. }
  1394. return $this->_inputLabel($fieldName, $label, $options);
  1395. }
  1396. /**
  1397. * Extracts a single option from an options array.
  1398. *
  1399. * @param string $name The name of the option to pull out.
  1400. * @param array $options The array of options you want to extract.
  1401. * @param mixed $default The default option value
  1402. * @return mixed the contents of the option or default
  1403. */
  1404. protected function _extractOption($name, $options, $default = null)
  1405. {
  1406. if (array_key_exists($name, $options)) {
  1407. return $options[$name];
  1408. }
  1409. return $default;
  1410. }
  1411. /**
  1412. * Generate a label for an input() call.
  1413. *
  1414. * $options can contain a hash of id overrides. These overrides will be
  1415. * used instead of the generated values if present.
  1416. *
  1417. * @param string $fieldName The name of the field to generate label for.
  1418. * @param string $label Label text.
  1419. * @param array $options Options for the label element.
  1420. * @return string Generated label element
  1421. */
  1422. protected function _inputLabel($fieldName, $label, $options)
  1423. {
  1424. $options += ['id' => null, 'input' => null, 'nestedInput' => false, 'templateVars' => []];
  1425. $labelAttributes = ['templateVars' => $options['templateVars']];
  1426. if (is_array($label)) {
  1427. $labelText = null;
  1428. if (isset($label['text'])) {
  1429. $labelText = $label['text'];
  1430. unset($label['text']);
  1431. }
  1432. $labelAttributes = array_merge($labelAttributes, $label);
  1433. } else {
  1434. $labelText = $label;
  1435. }
  1436. $labelAttributes['for'] = $options['id'];
  1437. if (in_array($options['type'], $this->_groupedInputTypes, true)) {
  1438. $labelAttributes['for'] = false;
  1439. }
  1440. if ($options['nestedInput']) {
  1441. $labelAttributes['input'] = $options['input'];
  1442. }
  1443. if (isset($options['escape'])) {
  1444. $labelAttributes['escape'] = $options['escape'];
  1445. }
  1446. return $this->label($fieldName, $labelText, $labelAttributes);
  1447. }
  1448. /**
  1449. * Creates a checkbox input widget.
  1450. *
  1451. * ### Options:
  1452. *
  1453. * - `value` - the value of the checkbox
  1454. * - `checked` - boolean indicate that this checkbox is checked.
  1455. * - `hiddenField` - boolean to indicate if you want the results of checkbox() to include
  1456. * a hidden input with a value of ''.
  1457. * - `disabled` - create a disabled input.
  1458. * - `default` - Set the default value for the checkbox. This allows you to start checkboxes
  1459. * as checked, without having to check the POST data. A matching POST data value, will overwrite
  1460. * the default value.
  1461. *
  1462. * @param string $fieldName Name of a field, like this "modelname.fieldname"
  1463. * @param array $options Array of HTML attributes.
  1464. * @return string|array An HTML text input element.
  1465. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-checkboxes
  1466. */
  1467. public function checkbox($fieldName, array $options = [])
  1468. {
  1469. $options += ['hiddenField' => true, 'value' => 1];
  1470. // Work around value=>val translations.
  1471. $value = $options['value'];
  1472. unset($options['value']);
  1473. $options = $this->_initInputField($fieldName, $options);
  1474. $options['value'] = $value;
  1475. $output = '';
  1476. if ($options['hiddenField']) {
  1477. $hiddenOptions = [
  1478. 'name' => $options['name'],
  1479. 'value' => $options['hiddenField'] !== true && $options['hiddenField'] !== '_split' ? $options['hiddenField'] : '0',
  1480. 'form' => isset($options['form']) ? $options['form'] : null,
  1481. 'secure' => false
  1482. ];
  1483. if (isset($options['disabled']) && $options['disabled']) {
  1484. $hiddenOptions['disabled'] = 'disabled';
  1485. }
  1486. $output = $this->hidden($fieldName, $hiddenOptions);
  1487. }
  1488. if ($options['hiddenField'] === '_split') {
  1489. unset($options['hiddenField'], $options['type']);
  1490. return ['hidden' => $output, 'input' => $this->widget('checkbox', $options)];
  1491. }
  1492. unset($options['hiddenField'], $options['type']);
  1493. return $output . $this->widget('checkbox', $options);
  1494. }
  1495. /**
  1496. * Creates a set of radio widgets.
  1497. *
  1498. * ### Attributes:
  1499. *
  1500. * - `value` - Indicates the value when this radio button is checked.
  1501. * - `label` - Either `false` to disable label around the widget or an array of attributes for
  1502. * the label tag. `selected` will be added to any classes e.g. `'class' => 'myclass'` where widget
  1503. * is checked
  1504. * - `hiddenField` - boolean to indicate if you want the results of radio() to include
  1505. * a hidden input with a value of ''. This is useful for creating radio sets that are non-continuous.
  1506. * - `disabled` - Set to `true` or `disabled` to disable all the radio buttons. Use an array of
  1507. * values to disable specific radio buttons.
  1508. * - `empty` - Set to `true` to create an input with the value '' as the first option. When `true`
  1509. * the radio label will be 'empty'. Set this option to a string to control the label value.
  1510. *
  1511. * @param string $fieldName Name of a field, like this "modelname.fieldname"
  1512. * @param array|\Traversable $options Radio button options array.
  1513. * @param array $attributes Array of attributes.
  1514. * @return string Completed radio widget set.
  1515. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-radio-buttons
  1516. */
  1517. public function radio($fieldName, $options = [], array $attributes = [])
  1518. {
  1519. $attributes['options'] = $options;
  1520. $attributes['idPrefix'] = $this->_idPrefix;
  1521. $attributes = $this->_initInputField($fieldName, $attributes);
  1522. $hiddenField = isset($attributes['hiddenField']) ? $attributes['hiddenField'] : true;
  1523. unset($attributes['hiddenField']);
  1524. $radio = $this->widget('radio', $attributes);
  1525. $hidden = '';
  1526. if ($hiddenField) {
  1527. $hidden = $this->hidden($fieldName, [
  1528. 'value' => $hiddenField === true ? '' : $hiddenField,
  1529. 'form' => isset($attributes['form']) ? $attributes['form'] : null,
  1530. 'name' => $attributes['name'],
  1531. ]);
  1532. }
  1533. return $hidden . $radio;
  1534. }
  1535. /**
  1536. * Missing method handler - implements various simple input types. Is used to create inputs
  1537. * of various types. e.g. `$this->Form->text();` will create `<input type="text" />` while
  1538. * `$this->Form->range();` will create `<input type="range" />`
  1539. *
  1540. * ### Usage
  1541. *
  1542. * ```
  1543. * $this->Form->search('User.query', ['value' => 'test']);
  1544. * ```
  1545. *
  1546. * Will make an input like:
  1547. *
  1548. * `<input type="search" id="UserQuery" name="User[query]" value="test" />`
  1549. *
  1550. * The first argument to an input type should always be the fieldname, in `Model.field` format.
  1551. * The second argument should always be an array of attributes for the input.
  1552. *
  1553. * @param string $method Method name / input type to make.
  1554. * @param array $params Parameters for the method call
  1555. * @return string Formatted input method.
  1556. * @throws \Cake\Core\Exception\Exception When there are no params for the method call.
  1557. */
  1558. public function __call($method, $params)
  1559. {
  1560. $options = [];
  1561. if (empty($params)) {
  1562. throw new Exception(sprintf('Missing field name for FormHelper::%s', $method));
  1563. }
  1564. if (isset($params[1])) {
  1565. $options = $params[1];
  1566. }
  1567. if (!isset($options['type'])) {
  1568. $options['type'] = $method;
  1569. }
  1570. $options = $this->_initInputField($params[0], $options);
  1571. return $this->widget($options['type'], $options);
  1572. }
  1573. /**
  1574. * Creates a textarea widget.
  1575. *
  1576. * ### Options:
  1577. *
  1578. * - `escape` - Whether or not the contents of the textarea should be escaped. Defaults to true.
  1579. *
  1580. * @param string $fieldName Name of a field, in the form "modelname.fieldname"
  1581. * @param array $options Array of HTML attributes, and special options above.
  1582. * @return string A generated HTML text input element
  1583. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-textareas
  1584. */
  1585. public function textarea($fieldName, array $options = [])
  1586. {
  1587. $options = $this->_initInputField($fieldName, $options);
  1588. unset($options['type']);
  1589. return $this->widget('textarea', $options);
  1590. }
  1591. /**
  1592. * Creates a hidden input field.
  1593. *
  1594. * @param string $fieldName Name of a field, in the form of "modelname.fieldname"
  1595. * @param array $options Array of HTML attributes.
  1596. * @return string A generated hidden input
  1597. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-hidden-inputs
  1598. */
  1599. public function hidden($fieldName, array $options = [])
  1600. {
  1601. $options += ['required' => false, 'secure' => true];
  1602. $secure = $options['secure'];
  1603. unset($options['secure']);
  1604. $options = $this->_initInputField($fieldName, array_merge(
  1605. $options,
  1606. ['secure' => static::SECURE_SKIP]
  1607. ));
  1608. if ($secure === true) {
  1609. $this->_secure(true, $this->_secureFieldName($options['name']), (string)$options['val']);
  1610. }
  1611. $options['type'] = 'hidden';
  1612. return $this->widget('hidden', $options);
  1613. }
  1614. /**
  1615. * Creates file input widget.
  1616. *
  1617. * @param string $fieldName Name of a field, in the form "modelname.fieldname"
  1618. * @param array $options Array of HTML attributes.
  1619. * @return string A generated file input.
  1620. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-file-inputs
  1621. */
  1622. public function file($fieldName, array $options = [])
  1623. {
  1624. $options += ['secure' => true];
  1625. $options = $this->_initInputField($fieldName, $options);
  1626. unset($options['type']);
  1627. return $this->widget('file', $options);
  1628. }
  1629. /**
  1630. * Creates a `<button>` tag.
  1631. *
  1632. * The type attribute defaults to `type="submit"`
  1633. * You can change it to a different value by using `$options['type']`.
  1634. *
  1635. * ### Options:
  1636. *
  1637. * - `escape` - HTML entity encode the $title of the button. Defaults to false.
  1638. * - `confirm` - Confirm message to show. Form execution will only continue if confirmed then.
  1639. *
  1640. * @param string $title The button's caption. Not automatically HTML encoded
  1641. * @param array $options Array of options and HTML attributes.
  1642. * @return string A HTML button tag.
  1643. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-button-elements
  1644. */
  1645. public function button($title, array $options = [])
  1646. {
  1647. $options += ['type' => 'submit', 'escape' => false, 'secure' => false, 'confirm' => null];
  1648. $options['text'] = $title;
  1649. $confirmMessage = $options['confirm'];
  1650. unset($options['confirm']);
  1651. if ($confirmMessage) {
  1652. $options['onclick'] = $this->_confirm($confirmMessage, 'return true;', 'return false;', $options);
  1653. }
  1654. return $this->widget('button', $options);
  1655. }
  1656. /**
  1657. * Create a `<button>` tag with a surrounding `<form>` that submits via POST as default.
  1658. *
  1659. * This method creates a `<form>` element. So do not use this method in an already opened form.
  1660. * Instead use FormHelper::submit() or FormHelper::button() to create buttons inside opened forms.
  1661. *
  1662. * ### Options:
  1663. *
  1664. * - `data` - Array with key/value to pass in input hidden
  1665. * - `method` - Request method to use. Set to 'delete' or others to simulate
  1666. * HTTP/1.1 DELETE (or others) request. Defaults to 'post'.
  1667. * - `form` - Array with any option that FormHelper::create() can take
  1668. * - Other options is the same of button method.
  1669. * - `confirm` - Confirm message to show. Form execution will only continue if confirmed then.
  1670. *
  1671. * @param string $title The button's caption. Not automatically HTML encoded
  1672. * @param string|array $url URL as string or array
  1673. * @param array $options Array of options and HTML attributes.
  1674. * @return string A HTML button tag.
  1675. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-standalone-buttons-and-post-links
  1676. */
  1677. public function postButton($title, $url, array $options = [])
  1678. {
  1679. $formOptions = ['url' => $url];
  1680. if (isset($options['method'])) {
  1681. $formOptions['type'] = $options['method'];
  1682. unset($options['method']);
  1683. }
  1684. if (isset($options['form']) && is_array($options['form'])) {
  1685. $formOptions = $options['form'] + $formOptions;
  1686. unset($options['form']);
  1687. }
  1688. $out = $this->create(false, $formOptions);
  1689. if (isset($options['data']) && is_array($options['data'])) {
  1690. foreach (Hash::flatten($options['data']) as $key => $value) {
  1691. $out .= $this->hidden($key, ['value' => $value]);
  1692. }
  1693. unset($options['data']);
  1694. }
  1695. $out .= $this->button($title, $options);
  1696. $out .= $this->end();
  1697. return $out;
  1698. }
  1699. /**
  1700. * Creates an HTML link, but access the URL using the method you specify
  1701. * (defaults to POST). Requires javascript to be enabled in browser.
  1702. *
  1703. * This method creates a `<form>` element. If you want to use this method inside of an
  1704. * existing form, you must use the `block` option so that the new form is being set to
  1705. * a view block that can be rendered outside of the main form.
  1706. *
  1707. * If all you are looking for is a button to submit your form, then you should use
  1708. * `FormHelper::button()` or `FormHelper::submit()` instead.
  1709. *
  1710. * ### Options:
  1711. *
  1712. * - `data` - Array with key/value to pass in input hidden
  1713. * - `method` - Request method to use. Set to 'delete' to simulate
  1714. * HTTP/1.1 DELETE request. Defaults to 'post'.
  1715. * - `confirm` - Confirm message to show. Form execution will only continue if confirmed then.
  1716. * - `block` - Set to true to append form to view block "postLink" or provide
  1717. * custom block name.
  1718. * - Other options are the same of HtmlHelper::link() method.
  1719. * - The option `onclick` will be replaced.
  1720. *
  1721. * @param string $title The content to be wrapped by <a> tags.
  1722. * @param string|array|null $url Cake-relative URL or array of URL parameters, or
  1723. * external URL (starts with http://)
  1724. * @param array $options Array of HTML attributes.
  1725. * @return string An `<a />` element.
  1726. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-standalone-buttons-and-post-links
  1727. */
  1728. public function postLink($title, $url = null, array $options = [])
  1729. {
  1730. $options += ['block' => null, 'confirm' => null];
  1731. $requestMethod = 'POST';
  1732. if (!empty($options['method'])) {
  1733. $requestMethod = strtoupper($options['method']);
  1734. unset($options['method']);
  1735. }
  1736. $confirmMessage = $options['confirm'];
  1737. unset($options['confirm']);
  1738. $formName = str_replace('.', '', uniqid('post_', true));
  1739. $formOptions = [
  1740. 'name' => $formName,
  1741. 'style' => 'display:none;',
  1742. 'method' => 'post',
  1743. ];
  1744. if (isset($options['target'])) {
  1745. $formOptions['target'] = $options['target'];
  1746. unset($options['target']);
  1747. }
  1748. $templater = $this->templater();
  1749. $restoreAction = $this->_lastAction;
  1750. $this->_lastAction($url);
  1751. $action = $templater->formatAttributes([
  1752. 'action' => $this->Url->build($url),
  1753. 'escape' => false
  1754. ]);
  1755. $out = $this->formatTemplate('formStart', [
  1756. 'attrs' => $templater->formatAttributes($formOptions) . $action
  1757. ]);
  1758. $out .= $this->hidden('_method', [
  1759. 'value' => $requestMethod,
  1760. 'secure' => static::SECURE_SKIP
  1761. ]);
  1762. $out .= $this->_csrfField();
  1763. $fields = [];
  1764. if (isset($options['data']) && is_array($options['data'])) {
  1765. foreach (Hash::flatten($options['data']) as $key => $value) {
  1766. $fields[$key] = $value;
  1767. $out .= $this->hidden($key, ['value' => $value, 'secure' => static::SECURE_SKIP]);
  1768. }
  1769. unset($options['data']);
  1770. }
  1771. $out .= $this->secure($fields);
  1772. $out .= $this->formatTemplate('formEnd', []);
  1773. $this->_lastAction = $restoreAction;
  1774. if ($options['block']) {
  1775. if ($options['block'] === true) {
  1776. $options['block'] = __FUNCTION__;
  1777. }
  1778. $this->_View->append($options['block'], $out);
  1779. $out = '';
  1780. }
  1781. unset($options['block']);
  1782. $url = '#';
  1783. $onClick = 'document.' . $formName . '.submit();';
  1784. if ($confirmMessage) {
  1785. $confirm = $this->_confirm($confirmMessage, $onClick, '', $options);
  1786. } else {
  1787. $confirm = $onClick . ' ';
  1788. }
  1789. $confirm .= 'event.returnValue = false; return false;';
  1790. $options['onclick'] = $this->templater()->format('confirmJs', [
  1791. 'confirmMessage' => $this->_cleanConfirmMessage($confirmMessage),
  1792. 'formName' => $formName,
  1793. 'confirm' => $confirm
  1794. ]);
  1795. $out .= $this->Html->link($title, $url, $options);
  1796. return $out;
  1797. }
  1798. /**
  1799. * Creates a submit button element. This method will generate `<input />` elements that
  1800. * can be used to submit, and reset forms by using $options. image submits can be created by supplying an
  1801. * image path for $caption.
  1802. *
  1803. * ### Options
  1804. *
  1805. * - `type` - Set to 'reset' for reset inputs. Defaults to 'submit'
  1806. * - `templateVars` - Additional template variables for the input element and its container.
  1807. * - Other attributes will be assigned to the input element.
  1808. *
  1809. * @param string|null $caption The label appearing on the button OR if string contains :// or the
  1810. * extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension
  1811. * exists, AND the first character is /, image is relative to webroot,
  1812. * OR if the first character is not /, image is relative to webroot/img.
  1813. * @param array $options Array of options. See above.
  1814. * @return string A HTML submit button
  1815. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-buttons-and-submit-elements
  1816. */
  1817. public function submit($caption = null, array $options = [])
  1818. {
  1819. if (!is_string($caption) && empty($caption)) {
  1820. $caption = __d('cake', 'Submit');
  1821. }
  1822. $options += [
  1823. 'type' => 'submit',
  1824. 'secure' => false,
  1825. 'templateVars' => []
  1826. ];
  1827. if (isset($options['name'])) {
  1828. $this->_secure($options['secure'], $this->_secureFieldName($options['name']));
  1829. }
  1830. unset($options['secure']);
  1831. $isUrl = strpos($caption, '://') !== false;
  1832. $isImage = preg_match('/\.(jpg|jpe|jpeg|gif|png|ico)$/', $caption);
  1833. $type = $options['type'];
  1834. unset($options['type']);
  1835. if ($isUrl || $isImage) {
  1836. $unlockFields = ['x', 'y'];
  1837. if (isset($options['name'])) {
  1838. $unlockFields = [
  1839. $options['name'] . '_x',
  1840. $options['name'] . '_y'
  1841. ];
  1842. }
  1843. foreach ($unlockFields as $ignore) {
  1844. $this->unlockField($ignore);
  1845. }
  1846. $type = 'image';
  1847. }
  1848. if ($isUrl) {
  1849. $options['src'] = $caption;
  1850. } elseif ($isImage) {
  1851. if ($caption[0] !== '/') {
  1852. $url = $this->Url->webroot(Configure::read('App.imageBaseUrl') . $caption);
  1853. } else {
  1854. $url = $this->Url->webroot(trim($caption, '/'));
  1855. }
  1856. $url = $this->Url->assetTimestamp($url);
  1857. $options['src'] = $url;
  1858. } else {
  1859. $options['value'] = $caption;
  1860. }
  1861. $input = $this->formatTemplate('inputSubmit', [
  1862. 'type' => $type,
  1863. 'attrs' => $this->templater()->formatAttributes($options),
  1864. 'templateVars' => $options['templateVars']
  1865. ]);
  1866. return $this->formatTemplate('submitContainer', [
  1867. 'content' => $input,
  1868. 'templateVars' => $options['templateVars']
  1869. ]);
  1870. }
  1871. /**
  1872. * Returns a formatted SELECT element.
  1873. *
  1874. * ### Attributes:
  1875. *
  1876. * - `multiple` - show a multiple select box. If set to 'checkbox' multiple checkboxes will be
  1877. * created instead.
  1878. * - `empty` - If true, the empty select option is shown. If a string,
  1879. * that string is displayed as the empty element.
  1880. * - `escape` - If true contents of options will be HTML entity encoded. Defaults to true.
  1881. * - `val` The selected value of the input.
  1882. * - `disabled` - Control the disabled attribute. When creating a select box, set to true to disable the
  1883. * select box. Set to an array to disable specific option elements.
  1884. *
  1885. * ### Using options
  1886. *
  1887. * A simple array will create normal options:
  1888. *
  1889. * ```
  1890. * $options = [1 => 'one', 2 => 'two'];
  1891. * $this->Form->select('Model.field', $options));
  1892. * ```
  1893. *
  1894. * While a nested options array will create optgroups with options inside them.
  1895. * ```
  1896. * $options = [
  1897. * 1 => 'bill',
  1898. * 'fred' => [
  1899. * 2 => 'fred',
  1900. * 3 => 'fred jr.'
  1901. * ]
  1902. * ];
  1903. * $this->Form->select('Model.field', $options);
  1904. * ```
  1905. *
  1906. * If you have multiple options that need to have the same value attribute, you can
  1907. * use an array of arrays to express this:
  1908. *
  1909. * ```
  1910. * $options = [
  1911. * ['text' => 'United states', 'value' => 'USA'],
  1912. * ['text' => 'USA', 'value' => 'USA'],
  1913. * ];
  1914. * ```
  1915. *
  1916. * @param string $fieldName Name attribute of the SELECT
  1917. * @param array|\Traversable $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the
  1918. * SELECT element
  1919. * @param array $attributes The HTML attributes of the select element.
  1920. * @return string Formatted SELECT element
  1921. * @see \Cake\View\Helper\FormHelper::multiCheckbox() for creating multiple checkboxes.
  1922. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-select-pickers
  1923. */
  1924. public function select($fieldName, $options = [], array $attributes = [])
  1925. {
  1926. $attributes += [
  1927. 'disabled' => null,
  1928. 'escape' => true,
  1929. 'hiddenField' => true,
  1930. 'multiple' => null,
  1931. 'secure' => true,
  1932. 'empty' => false,
  1933. ];
  1934. if ($attributes['multiple'] === 'checkbox') {
  1935. unset($attributes['multiple'], $attributes['empty']);
  1936. return $this->multiCheckbox($fieldName, $options, $attributes);
  1937. }
  1938. unset($attributes['label']);
  1939. // Secure the field if there are options, or it's a multi select.
  1940. // Single selects with no options don't submit, but multiselects do.
  1941. if ($attributes['secure'] &&
  1942. empty($options) &&
  1943. empty($attributes['empty']) &&
  1944. empty($attributes['multiple'])
  1945. ) {
  1946. $attributes['secure'] = false;
  1947. }
  1948. $attributes = $this->_initInputField($fieldName, $attributes);
  1949. $attributes['options'] = $options;
  1950. $hidden = '';
  1951. if ($attributes['multiple'] && $attributes['hiddenField']) {
  1952. $hiddenAttributes = [
  1953. 'name' => $attributes['name'],
  1954. 'value' => '',
  1955. 'form' => isset($attributes['form']) ? $attributes['form'] : null,
  1956. 'secure' => false,
  1957. ];
  1958. $hidden = $this->hidden($fieldName, $hiddenAttributes);
  1959. }
  1960. unset($attributes['hiddenField'], $attributes['type']);
  1961. return $hidden . $this->widget('select', $attributes);
  1962. }
  1963. /**
  1964. * Creates a set of checkboxes out of options.
  1965. *
  1966. * ### Options
  1967. *
  1968. * - `escape` - If true contents of options will be HTML entity encoded. Defaults to true.
  1969. * - `val` The selected value of the input.
  1970. * - `class` - When using multiple = checkbox the class name to apply to the divs. Defaults to 'checkbox'.
  1971. * - `disabled` - Control the disabled attribute. When creating checkboxes, `true` will disable all checkboxes.
  1972. * You can also set disabled to a list of values you want to disable when creating checkboxes.
  1973. * - `hiddenField` - Set to false to remove the hidden field that ensures a value
  1974. * is always submitted.
  1975. * - `label` - Either `false` to disable label around the widget or an array of attributes for
  1976. * the label tag. `selected` will be added to any classes e.g. `'class' => 'myclass'` where
  1977. * widget is checked
  1978. *
  1979. * Can be used in place of a select box with the multiple attribute.
  1980. *
  1981. * @param string $fieldName Name attribute of the SELECT
  1982. * @param array|\Traversable $options Array of the OPTION elements
  1983. * (as 'value'=>'Text' pairs) to be used in the checkboxes element.
  1984. * @param array $attributes The HTML attributes of the select element.
  1985. * @return string Formatted SELECT element
  1986. * @see \Cake\View\Helper\FormHelper::select() for supported option formats.
  1987. */
  1988. public function multiCheckbox($fieldName, $options, array $attributes = [])
  1989. {
  1990. $attributes += [
  1991. 'disabled' => null,
  1992. 'escape' => true,
  1993. 'hiddenField' => true,
  1994. 'secure' => true,
  1995. ];
  1996. $attributes = $this->_initInputField($fieldName, $attributes);
  1997. $attributes['options'] = $options;
  1998. $attributes['idPrefix'] = $this->_idPrefix;
  1999. $hidden = '';
  2000. if ($attributes['hiddenField']) {
  2001. $hiddenAttributes = [
  2002. 'name' => $attributes['name'],
  2003. 'value' => '',
  2004. 'secure' => false,
  2005. 'disabled' => $attributes['disabled'] === true || $attributes['disabled'] === 'disabled',
  2006. ];
  2007. $hidden = $this->hidden($fieldName, $hiddenAttributes);
  2008. }
  2009. unset($attributes['hiddenField']);
  2010. return $hidden . $this->widget('multicheckbox', $attributes);
  2011. }
  2012. /**
  2013. * Helper method for the various single datetime component methods.
  2014. *
  2015. * @param array $options The options array.
  2016. * @param string $keep The option to not disable.
  2017. * @return array
  2018. */
  2019. protected function _singleDatetime($options, $keep)
  2020. {
  2021. $off = array_diff($this->_datetimeParts, [$keep]);
  2022. $off = array_combine(
  2023. $off,
  2024. array_fill(0, count($off), false)
  2025. );
  2026. $attributes = array_diff_key(
  2027. $options,
  2028. array_flip(array_merge($this->_datetimeOptions, ['value', 'empty']))
  2029. );
  2030. $options = $options + $off + [$keep => $attributes];
  2031. if (isset($options['value'])) {
  2032. $options['val'] = $options['value'];
  2033. }
  2034. return $options;
  2035. }
  2036. /**
  2037. * Returns a SELECT element for days.
  2038. *
  2039. * ### Options:
  2040. *
  2041. * - `empty` - If true, the empty select option is shown. If a string,
  2042. * that string is displayed as the empty element.
  2043. * - `value` The selected value of the input.
  2044. *
  2045. * @param string|null $fieldName Prefix name for the SELECT element
  2046. * @param array $options Options & HTML attributes for the select element
  2047. * @return string A generated day select box.
  2048. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-day-inputs
  2049. */
  2050. public function day($fieldName = null, array $options = [])
  2051. {
  2052. $options = $this->_singleDatetime($options, 'day');
  2053. if (isset($options['val']) && $options['val'] > 0 && $options['val'] <= 31) {
  2054. $options['val'] = [
  2055. 'year' => date('Y'),
  2056. 'month' => date('m'),
  2057. 'day' => (int)$options['val']
  2058. ];
  2059. }
  2060. return $this->dateTime($fieldName, $options);
  2061. }
  2062. /**
  2063. * Returns a SELECT element for years
  2064. *
  2065. * ### Attributes:
  2066. *
  2067. * - `empty` - If true, the empty select option is shown. If a string,
  2068. * that string is displayed as the empty element.
  2069. * - `orderYear` - Ordering of year values in select options.
  2070. * Possible values 'asc', 'desc'. Default 'desc'
  2071. * - `value` The selected value of the input.
  2072. * - `maxYear` The max year to appear in the select element.
  2073. * - `minYear` The min year to appear in the select element.
  2074. *
  2075. * @param string $fieldName Prefix name for the SELECT element
  2076. * @param array $options Options & attributes for the select elements.
  2077. * @return string Completed year select input
  2078. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-year-inputs
  2079. */
  2080. public function year($fieldName, array $options = [])
  2081. {
  2082. $options = $this->_singleDatetime($options, 'year');
  2083. $len = isset($options['val']) ? strlen($options['val']) : 0;
  2084. if (isset($options['val']) && $len > 0 && $len < 5) {
  2085. $options['val'] = [
  2086. 'year' => (int)$options['val'],
  2087. 'month' => date('m'),
  2088. 'day' => date('d')
  2089. ];
  2090. }
  2091. return $this->dateTime($fieldName, $options);
  2092. }
  2093. /**
  2094. * Returns a SELECT element for months.
  2095. *
  2096. * ### Options:
  2097. *
  2098. * - `monthNames` - If false, 2 digit numbers will be used instead of text.
  2099. * If an array, the given array will be used.
  2100. * - `empty` - If true, the empty select option is shown. If a string,
  2101. * that string is displayed as the empty element.
  2102. * - `value` The selected value of the input.
  2103. *
  2104. * @param string $fieldName Prefix name for the SELECT element
  2105. * @param array $options Attributes for the select element
  2106. * @return string A generated month select dropdown.
  2107. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-month-inputs
  2108. */
  2109. public function month($fieldName, array $options = [])
  2110. {
  2111. $options = $this->_singleDatetime($options, 'month');
  2112. if (isset($options['val']) && $options['val'] > 0 && $options['val'] <= 12) {
  2113. $options['val'] = [
  2114. 'year' => date('Y'),
  2115. 'month' => (int)$options['val'],
  2116. 'day' => date('d')
  2117. ];
  2118. }
  2119. return $this->dateTime($fieldName, $options);
  2120. }
  2121. /**
  2122. * Returns a SELECT element for hours.
  2123. *
  2124. * ### Attributes:
  2125. *
  2126. * - `empty` - If true, the empty select option is shown. If a string,
  2127. * that string is displayed as the empty element.
  2128. * - `value` The selected value of the input.
  2129. * - `format` Set to 12 or 24 to use 12 or 24 hour formatting. Defaults to 24.
  2130. *
  2131. * @param string $fieldName Prefix name for the SELECT element
  2132. * @param array $options List of HTML attributes
  2133. * @return string Completed hour select input
  2134. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-hour-inputs
  2135. */
  2136. public function hour($fieldName, array $options = [])
  2137. {
  2138. $options += ['format' => 24];
  2139. $options = $this->_singleDatetime($options, 'hour');
  2140. $options['timeFormat'] = $options['format'];
  2141. unset($options['format']);
  2142. if (isset($options['val']) && $options['val'] > 0 && $options['val'] <= 24) {
  2143. $options['val'] = [
  2144. 'hour' => (int)$options['val'],
  2145. 'minute' => date('i'),
  2146. ];
  2147. }
  2148. return $this->dateTime($fieldName, $options);
  2149. }
  2150. /**
  2151. * Returns a SELECT element for minutes.
  2152. *
  2153. * ### Attributes:
  2154. *
  2155. * - `empty` - If true, the empty select option is shown. If a string,
  2156. * that string is displayed as the empty element.
  2157. * - `value` The selected value of the input.
  2158. * - `interval` The interval that minute options should be created at.
  2159. * - `round` How you want the value rounded when it does not fit neatly into an
  2160. * interval. Accepts 'up', 'down', and null.
  2161. *
  2162. * @param string $fieldName Prefix name for the SELECT element
  2163. * @param array $options Array of options.
  2164. * @return string Completed minute select input.
  2165. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-minute-inputs
  2166. */
  2167. public function minute($fieldName, array $options = [])
  2168. {
  2169. $options = $this->_singleDatetime($options, 'minute');
  2170. if (isset($options['val']) && $options['val'] > 0 && $options['val'] <= 60) {
  2171. $options['val'] = [
  2172. 'hour' => date('H'),
  2173. 'minute' => (int)$options['val'],
  2174. ];
  2175. }
  2176. return $this->dateTime($fieldName, $options);
  2177. }
  2178. /**
  2179. * Returns a SELECT element for AM or PM.
  2180. *
  2181. * ### Attributes:
  2182. *
  2183. * - `empty` - If true, the empty select option is shown. If a string,
  2184. * that string is displayed as the empty element.
  2185. * - `value` The selected value of the input.
  2186. *
  2187. * @param string $fieldName Prefix name for the SELECT element
  2188. * @param array $options Array of options
  2189. * @return string Completed meridian select input
  2190. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-meridian-inputs
  2191. */
  2192. public function meridian($fieldName, array $options = [])
  2193. {
  2194. $options = $this->_singleDatetime($options, 'meridian');
  2195. if (isset($options['val'])) {
  2196. $hour = date('H');
  2197. $options['val'] = [
  2198. 'hour' => $hour,
  2199. 'minute' => (int)$options['val'],
  2200. 'meridian' => $hour > 11 ? 'pm' : 'am',
  2201. ];
  2202. }
  2203. return $this->dateTime($fieldName, $options);
  2204. }
  2205. /**
  2206. * Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
  2207. *
  2208. * ### Date Options:
  2209. *
  2210. * - `empty` - If true, the empty select option is shown. If a string,
  2211. * that string is displayed as the empty element.
  2212. * - `value` | `default` The default value to be used by the input. A value in `$this->data`
  2213. * matching the field name will override this value. If no default is provided `time()` will be used.
  2214. * - `monthNames` If false, 2 digit numbers will be used instead of text.
  2215. * If an array, the given array will be used.
  2216. * - `minYear` The lowest year to use in the year select
  2217. * - `maxYear` The maximum year to use in the year select
  2218. * - `orderYear` - Order of year values in select options.
  2219. * Possible values 'asc', 'desc'. Default 'desc'.
  2220. *
  2221. * ### Time options:
  2222. *
  2223. * - `empty` - If true, the empty select option is shown. If a string,
  2224. * - `value` | `default` The default value to be used by the input. A value in `$this->data`
  2225. * matching the field name will override this value. If no default is provided `time()` will be used.
  2226. * - `timeFormat` The time format to use, either 12 or 24.
  2227. * - `interval` The interval for the minutes select. Defaults to 1
  2228. * - `round` - Set to `up` or `down` if you want to force rounding in either direction. Defaults to null.
  2229. * - `second` Set to true to enable seconds drop down.
  2230. *
  2231. * To control the order of inputs, and any elements/content between the inputs you
  2232. * can override the `dateWidget` template. By default the `dateWidget` template is:
  2233. *
  2234. * `{{month}}{{day}}{{year}}{{hour}}{{minute}}{{second}}{{meridian}}`
  2235. *
  2236. * @param string $fieldName Prefix name for the SELECT element
  2237. * @param array $options Array of Options
  2238. * @return string Generated set of select boxes for the date and time formats chosen.
  2239. * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-date-and-time-inputs
  2240. */
  2241. public function dateTime($fieldName, array $options = [])
  2242. {
  2243. $options += [
  2244. 'empty' => true,
  2245. 'value' => null,
  2246. 'interval' => 1,
  2247. 'round' => null,
  2248. 'monthNames' => true,
  2249. 'minYear' => null,
  2250. 'maxYear' => null,
  2251. 'orderYear' => 'desc',
  2252. 'timeFormat' => 24,
  2253. 'second' => false,
  2254. ];
  2255. $options = $this->_initInputField($fieldName, $options);
  2256. $options = $this->_datetimeOptions($options);
  2257. return $this->widget('datetime', $options);
  2258. }
  2259. /**
  2260. * Helper method for converting from FormHelper options data to widget format.
  2261. *
  2262. * @param array $options Options to convert.
  2263. * @return array Converted options.
  2264. */
  2265. protected function _datetimeOptions($options)
  2266. {
  2267. foreach ($this->_datetimeParts as $type) {
  2268. if (!array_key_exists($type, $options)) {
  2269. $options[$type] = [];
  2270. }
  2271. if ($options[$type] === true) {
  2272. $options[$type] = [];
  2273. }
  2274. // Pass empty options to each type.
  2275. if (!empty($options['empty']) &&
  2276. is_array($options[$type])
  2277. ) {
  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. }