FormHelper.php 75 KB

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