FormHelper.php 97 KB

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