FormHelper.php 71 KB

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