FormHelper.php 96 KB

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