FormHelper.php 73 KB

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