FormHelper.php 69 KB

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