FormHelper.php 70 KB

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