FormHelper.php 72 KB

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