FormHelper.php 98 KB

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