FormHelper.php 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516
  1. <?php
  2. /**
  3. * Automatic generation of HTML FORMs from given data.
  4. *
  5. * Used for scaffolding.
  6. *
  7. * PHP 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package Cake.View.Helper
  18. * @since CakePHP(tm) v 0.10.0.1076
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. App::uses('AppHelper', 'View/Helper');
  22. /**
  23. * Form helper library.
  24. *
  25. * Automatic generation of HTML FORMs from given data.
  26. *
  27. * @package Cake.View.Helper
  28. * @property HtmlHelper $Html
  29. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html
  30. */
  31. class FormHelper extends AppHelper {
  32. /**
  33. * Other helpers used by FormHelper
  34. *
  35. * @var array
  36. */
  37. public $helpers = array('Html');
  38. /**
  39. * Options used by DateTime fields
  40. *
  41. * @var array
  42. */
  43. protected $_options = array(
  44. 'day' => array(), 'minute' => array(), 'hour' => array(),
  45. 'month' => array(), 'year' => array(), 'meridian' => array()
  46. );
  47. /**
  48. * List of fields created, used with secure forms.
  49. *
  50. * @var array
  51. */
  52. public $fields = array();
  53. /**
  54. * Constant used internally to skip the securing process,
  55. * and neither add the field to the hash or to the unlocked fields.
  56. *
  57. * @var string
  58. */
  59. const SECURE_SKIP = 'skip';
  60. /**
  61. * Defines the type of form being created. Set by FormHelper::create().
  62. *
  63. * @var string
  64. */
  65. public $requestType = null;
  66. /**
  67. * The default model being used for the current form.
  68. *
  69. * @var string
  70. */
  71. public $defaultModel = null;
  72. /**
  73. * Persistent default options used by input(). Set by FormHelper::create().
  74. *
  75. * @var array
  76. */
  77. protected $_inputDefaults = array();
  78. /**
  79. * An array of fieldnames that have been excluded from
  80. * the Token hash used by SecurityComponent's validatePost method
  81. *
  82. * @see FormHelper::_secure()
  83. * @see SecurityComponent::validatePost()
  84. * @var array
  85. */
  86. protected $_unlockedFields = array();
  87. /**
  88. * Holds the model references already loaded by this helper
  89. * product of trying to inspect them out of field names
  90. *
  91. * @var array
  92. */
  93. protected $_models = array();
  94. /**
  95. * Holds all the validation errors for models loaded and inspected
  96. * it can also be set manually to be able to display custom error messages
  97. * in the any of the input fields generated by this helper
  98. *
  99. * @var array
  100. */
  101. public $validationErrors = array();
  102. /**
  103. * Copies the validationErrors variable from the View object into this instance
  104. *
  105. * @param View $View The View this helper is being attached to.
  106. * @param array $settings Configuration settings for the helper.
  107. */
  108. public function __construct(View $View, $settings = array()) {
  109. parent::__construct($View, $settings);
  110. $this->validationErrors =& $View->validationErrors;
  111. }
  112. /**
  113. * Guess the location for a model based on its name and tries to create a new instance
  114. * or get an already created instance of the model
  115. *
  116. * @param string $model
  117. * @return Model model instance
  118. */
  119. protected function _getModel($model) {
  120. $object = null;
  121. if (!$model || $model === 'Model') {
  122. return $object;
  123. }
  124. if (array_key_exists($model, $this->_models)) {
  125. return $this->_models[$model];
  126. }
  127. if (ClassRegistry::isKeySet($model)) {
  128. $object = ClassRegistry::getObject($model);
  129. } elseif (isset($this->request->params['models'][$model])) {
  130. $plugin = $this->request->params['models'][$model]['plugin'];
  131. $plugin .= ($plugin) ? '.' : null;
  132. $object = ClassRegistry::init(array(
  133. 'class' => $plugin . $this->request->params['models'][$model]['className'],
  134. 'alias' => $model
  135. ));
  136. } else {
  137. $object = ClassRegistry::init($model, true);
  138. }
  139. $this->_models[$model] = $object;
  140. if (!$object) {;
  141. return null;
  142. }
  143. $this->fieldset[$model] = array('fields' => null, 'key' => $object->primaryKey, 'validates' => null);
  144. return $object;
  145. }
  146. /**
  147. * Inspects the model properties to extract information from them.
  148. * Currently it can extract information from the the fields, the primary key and required fields
  149. *
  150. * The $key parameter accepts the following list of values:
  151. *
  152. * - key: Returns the name of the primary key for the model
  153. * - fields: Returns the model schema
  154. * - validates: returns the list of fields that are required
  155. * - errors: returns the list of validation errors
  156. *
  157. * If the $field parameter is passed if will return the information for that sole field.
  158. *
  159. * `$this->_introspectModel('Post', 'fields', 'title');` will return the schema information for title column
  160. *
  161. * @param string $model name of the model to extract information from
  162. * @param string $key name of the special information key to obtain (key, fields, validates, errors)
  163. * @param string $field name of the model field to get information from
  164. * @return mixed information extracted for the special key and field in a model
  165. */
  166. protected function _introspectModel($model, $key, $field = null) {
  167. $object = $this->_getModel($model);
  168. if (!$object) {
  169. return;
  170. }
  171. if ($key === 'key') {
  172. return $this->fieldset[$model]['key'] = $object->primaryKey;
  173. }
  174. if ($key === 'fields') {
  175. if (!isset($this->fieldset[$model]['fields'])) {
  176. $fields = $this->fieldset[$model]['fields'] = $object->schema();
  177. foreach ($object->hasAndBelongsToMany as $alias => $assocData) {
  178. $this->fieldset[$object->alias]['fields'][$alias] = array('type' => 'multiple');
  179. }
  180. }
  181. if (empty($field)) {
  182. return $this->fieldset[$model]['fields'];
  183. } elseif (isset($this->fieldset[$model]['fields'][$field])) {
  184. return $this->fieldset[$model]['fields'][$field];
  185. } else {
  186. return isset($object->hasAndBelongsToMany[$field]) ? array('type' => 'multiple') : null;
  187. }
  188. }
  189. if ($key === 'errors' && !isset($this->validationErrors[$model])) {
  190. $this->validationErrors[$model] =& $object->validationErrors;
  191. return $this->validationErrors[$model];
  192. } elseif ($key === 'errors' && isset($this->validationErrors[$model])) {
  193. return $this->validationErrors[$model];
  194. }
  195. if ($key === 'validates' && !isset($this->fieldset[$model]['validates'])) {
  196. $validates = array();
  197. if (!empty($object->validate)) {
  198. foreach ($object->validate as $validateField => $validateProperties) {
  199. if ($this->_isRequiredField($validateProperties)) {
  200. $validates[$validateField] = true;
  201. }
  202. }
  203. }
  204. $this->fieldset[$model]['validates'] = $validates;
  205. }
  206. if ($key === 'validates') {
  207. if (empty($field)) {
  208. return $this->fieldset[$model]['validates'];
  209. } else {
  210. return isset($this->fieldset[$model]['validates'][$field]) ?
  211. $this->fieldset[$model]['validates'] : null;
  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 array $validateProperties
  219. * @return boolean true if field is required to be filled, false otherwise
  220. */
  221. protected function _isRequiredField($validateProperties) {
  222. $required = false;
  223. if (is_array($validateProperties)) {
  224. $dims = Set::countDim($validateProperties);
  225. if ($dims == 1 || ($dims == 2 && isset($validateProperties['rule']))) {
  226. $validateProperties = array($validateProperties);
  227. }
  228. foreach ($validateProperties as $rule => $validateProp) {
  229. if (isset($validateProp['allowEmpty']) && $validateProp['allowEmpty'] === true) {
  230. return false;
  231. }
  232. $rule = isset($validateProp['rule']) ? $validateProp['rule'] : false;
  233. $required = $rule || empty($validateProp);
  234. if ($required) {
  235. break;
  236. }
  237. }
  238. }
  239. return $required;
  240. }
  241. /**
  242. * Returns false if given form field described by the current entity has no errors.
  243. * Otherwise it returns the validation message
  244. *
  245. * @return mixed Either false when there or no errors, or the error
  246. * string. The error string could be ''.
  247. */
  248. public function tagIsInvalid() {
  249. $entity = $this->entity();
  250. $model = array_shift($entity);
  251. $errors = array();
  252. if (!empty($entity) && isset($this->validationErrors[$model])) {
  253. $errors = $this->validationErrors[$model];
  254. }
  255. if (!empty($entity) && empty($errors)) {
  256. $errors = $this->_introspectModel($model, 'errors');
  257. }
  258. if (empty($errors)) {
  259. return false;
  260. }
  261. $error = Set::classicExtract($errors, join('.', $entity));
  262. return $error === null ? false : $error;
  263. }
  264. /**
  265. * Returns an HTML FORM element.
  266. *
  267. * ### Options:
  268. *
  269. * - `type` Form method defaults to POST
  270. * - `action` The controller action the form submits to, (optional).
  271. * - `url` The url the form submits to. Can be a string or a url array. If you use 'url'
  272. * you should leave 'action' undefined.
  273. * - `default` Allows for the creation of Ajax forms. Set this to false to prevent the default event handler.
  274. * Will create an onsubmit attribute if it doesn't not exist. If it does, default action suppression
  275. * will be appended.
  276. * - `onsubmit` Used in conjunction with 'default' to create ajax forms.
  277. * - `inputDefaults` set the default $options for FormHelper::input(). Any options that would
  278. * be set when using FormHelper::input() can be set here. Options set with `inputDefaults`
  279. * can be overridden when calling input()
  280. * - `encoding` Set the accept-charset encoding for the form. Defaults to `Configure::read('App.encoding')`
  281. *
  282. * @param string $model The model object which the form is being defined for. Should
  283. * include the plugin name for plugin forms. e.g. `ContactManager.Contact`.
  284. * @param array $options An array of html attributes and options.
  285. * @return string An formatted opening FORM tag.
  286. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-create
  287. */
  288. public function create($model = null, $options = array()) {
  289. $created = $id = false;
  290. $append = '';
  291. if (is_array($model) && empty($options)) {
  292. $options = $model;
  293. $model = null;
  294. }
  295. if (empty($model) && $model !== false && !empty($this->request->params['models'])) {
  296. $model = key($this->request->params['models']);
  297. $this->defaultModel = $model;
  298. } elseif (empty($model) && empty($this->request->params['models'])) {
  299. $model = false;
  300. }
  301. $key = null;
  302. if ($model !== false) {
  303. $object = $this->_getModel($model);
  304. $key = $this->_introspectModel($model, 'key');
  305. $this->setEntity($model, true);
  306. }
  307. if ($model !== false && $key) {
  308. $recordExists = (
  309. isset($this->request->data[$model]) &&
  310. !empty($this->request->data[$model][$key]) &&
  311. !is_array($this->request->data[$model][$key])
  312. );
  313. if ($recordExists) {
  314. $created = true;
  315. $id = $this->request->data[$model][$key];
  316. }
  317. }
  318. $options = array_merge(array(
  319. 'type' => ($created && empty($options['action'])) ? 'put' : 'post',
  320. 'action' => null,
  321. 'url' => null,
  322. 'default' => true,
  323. 'encoding' => strtolower(Configure::read('App.encoding')),
  324. 'inputDefaults' => array()),
  325. $options);
  326. $this->_inputDefaults = $options['inputDefaults'];
  327. unset($options['inputDefaults']);
  328. if (!isset($options['id'])) {
  329. $domId = isset($options['action']) ? $options['action'] : $this->request['action'];
  330. $options['id'] = $this->domId($domId . 'Form');
  331. }
  332. if ($options['action'] === null && $options['url'] === null) {
  333. $options['action'] = $this->request->here(false);
  334. } elseif (empty($options['url']) || is_array($options['url'])) {
  335. if (empty($options['url']['controller'])) {
  336. if (!empty($model) && $model != $this->defaultModel) {
  337. $options['url']['controller'] = Inflector::underscore(Inflector::pluralize($model));
  338. } elseif (!empty($this->request->params['controller'])) {
  339. $options['url']['controller'] = Inflector::underscore($this->request->params['controller']);
  340. }
  341. }
  342. if (empty($options['action'])) {
  343. $options['action'] = $this->request->params['action'];
  344. }
  345. $plugin = null;
  346. if ($this->plugin) {
  347. $plugin = Inflector::underscore($this->plugin);
  348. }
  349. $actionDefaults = array(
  350. 'plugin' => $plugin,
  351. 'controller' => $this->_View->viewPath,
  352. 'action' => $options['action'],
  353. );
  354. $options['action'] = array_merge($actionDefaults, (array)$options['url']);
  355. if (empty($options['action'][0]) && !empty($id)) {
  356. $options['action'][0] = $id;
  357. }
  358. } elseif (is_string($options['url'])) {
  359. $options['action'] = $options['url'];
  360. }
  361. unset($options['url']);
  362. switch (strtolower($options['type'])) {
  363. case 'get':
  364. $htmlAttributes['method'] = 'get';
  365. break;
  366. case 'file':
  367. $htmlAttributes['enctype'] = 'multipart/form-data';
  368. $options['type'] = ($created) ? 'put' : 'post';
  369. case 'post':
  370. case 'put':
  371. case 'delete':
  372. $append .= $this->hidden('_method', array(
  373. 'name' => '_method', 'value' => strtoupper($options['type']), 'id' => null,
  374. 'secure' => self::SECURE_SKIP
  375. ));
  376. default:
  377. $htmlAttributes['method'] = 'post';
  378. break;
  379. }
  380. $this->requestType = strtolower($options['type']);
  381. $action = $this->url($options['action']);
  382. unset($options['type'], $options['action']);
  383. if ($options['default'] == false) {
  384. if (!isset($options['onsubmit'])) {
  385. $options['onsubmit'] = '';
  386. }
  387. $htmlAttributes['onsubmit'] = $options['onsubmit'] . 'event.returnValue = false; return false;';
  388. }
  389. unset($options['default']);
  390. if (!empty($options['encoding'])) {
  391. $htmlAttributes['accept-charset'] = $options['encoding'];
  392. unset($options['encoding']);
  393. }
  394. $htmlAttributes = array_merge($options, $htmlAttributes);
  395. $this->fields = array();
  396. $append .= $this->_csrfField();
  397. if (!empty($append)) {
  398. $append = $this->Html->useTag('block', ' style="display:none;"', $append);
  399. }
  400. if ($model !== false) {
  401. $this->setEntity($model, true);
  402. $this->_introspectModel($model, 'fields');
  403. }
  404. return $this->Html->useTag('form', $action, $htmlAttributes) . $append;
  405. }
  406. /**
  407. * Return a CSRF input if the _Token is present.
  408. * Used to secure forms in conjunction with SecurityComponent
  409. *
  410. * @return string
  411. */
  412. protected function _csrfField() {
  413. if (empty($this->request->params['_Token'])) {
  414. return '';
  415. }
  416. if (!empty($this->request['_Token']['unlockedFields'])) {
  417. foreach ((array)$this->request['_Token']['unlockedFields'] as $unlocked) {
  418. $this->_unlockedFields[] = $unlocked;
  419. }
  420. }
  421. return $this->hidden('_Token.key', array(
  422. 'value' => $this->request->params['_Token']['key'], 'id' => 'Token' . mt_rand(),
  423. 'secure' => self::SECURE_SKIP
  424. ));
  425. }
  426. /**
  427. * Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden
  428. * input fields where appropriate.
  429. *
  430. * If $options is set a form submit button will be created. Options can be either a string or an array.
  431. *
  432. * {{{
  433. * array usage:
  434. *
  435. * array('label' => 'save'); value="save"
  436. * array('label' => 'save', 'name' => 'Whatever'); value="save" name="Whatever"
  437. * array('name' => 'Whatever'); value="Submit" name="Whatever"
  438. * array('label' => 'save', 'name' => 'Whatever', 'div' => 'good') <div class="good"> value="save" name="Whatever"
  439. * array('label' => 'save', 'name' => 'Whatever', 'div' => array('class' => 'good')); <div class="good"> value="save" name="Whatever"
  440. * }}}
  441. *
  442. * @param mixed $options as a string will use $options as the value of button,
  443. * @return string a closing FORM tag optional submit button.
  444. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#closing-the-form
  445. */
  446. public function end($options = null) {
  447. $out = null;
  448. $submit = null;
  449. if ($options !== null) {
  450. $submitOptions = array();
  451. if (is_string($options)) {
  452. $submit = $options;
  453. } else {
  454. if (isset($options['label'])) {
  455. $submit = $options['label'];
  456. unset($options['label']);
  457. }
  458. $submitOptions = $options;
  459. }
  460. $out .= $this->submit($submit, $submitOptions);
  461. }
  462. if (isset($this->request['_Token']) && !empty($this->request['_Token'])) {
  463. $out .= $this->secure($this->fields);
  464. $this->fields = array();
  465. }
  466. $this->setEntity(null);
  467. $out .= $this->Html->useTag('formend');
  468. $this->_View->modelScope = false;
  469. return $out;
  470. }
  471. /**
  472. * Generates a hidden field with a security hash based on the fields used in the form.
  473. *
  474. * @param array $fields The list of fields to use when generating the hash
  475. * @return string A hidden input field with a security hash
  476. */
  477. public function secure($fields = array()) {
  478. if (!isset($this->request['_Token']) || empty($this->request['_Token'])) {
  479. return;
  480. }
  481. $locked = array();
  482. $unlockedFields = $this->_unlockedFields;
  483. foreach ($fields as $key => $value) {
  484. if (!is_int($key)) {
  485. $locked[$key] = $value;
  486. unset($fields[$key]);
  487. }
  488. }
  489. sort($unlockedFields, SORT_STRING);
  490. sort($fields, SORT_STRING);
  491. ksort($locked, SORT_STRING);
  492. $fields += $locked;
  493. $locked = implode(array_keys($locked), '|');
  494. $unlocked = implode($unlockedFields, '|');
  495. $fields = Security::hash(serialize($fields) . $unlocked . Configure::read('Security.salt'));
  496. $out = $this->hidden('_Token.fields', array(
  497. 'value' => urlencode($fields . ':' . $locked),
  498. 'id' => 'TokenFields' . mt_rand()
  499. ));
  500. $out .= $this->hidden('_Token.unlocked', array(
  501. 'value' => urlencode($unlocked),
  502. 'id' => 'TokenUnlocked' . mt_rand()
  503. ));
  504. return $this->Html->useTag('block', ' style="display:none;"', $out);
  505. }
  506. /**
  507. * Add to or get the list of fields that are currently unlocked.
  508. * Unlocked fields are not included in the field hash used by SecurityComponent
  509. * unlocking a field once its been added to the list of secured fields will remove
  510. * it from the list of fields.
  511. *
  512. * @param string $name The dot separated name for the field.
  513. * @return mixed Either null, or the list of fields.
  514. */
  515. public function unlockField($name = null) {
  516. if ($name === null) {
  517. return $this->_unlockedFields;
  518. }
  519. if (!in_array($name, $this->_unlockedFields)) {
  520. $this->_unlockedFields[] = $name;
  521. }
  522. $index = array_search($name, $this->fields);
  523. if ($index !== false) {
  524. unset($this->fields[$index]);
  525. }
  526. unset($this->fields[$name]);
  527. }
  528. /**
  529. * Determine which fields of a form should be used for hash.
  530. * Populates $this->fields
  531. *
  532. * @param boolean $lock Whether this field should be part of the validation
  533. * or excluded as part of the unlockedFields.
  534. * @param mixed $field Reference to field to be secured
  535. * @param mixed $value Field value, if value should not be tampered with.
  536. * @return void
  537. */
  538. protected function _secure($lock, $field = null, $value = null) {
  539. if (!$field) {
  540. $field = $this->entity();
  541. } elseif (is_string($field)) {
  542. $field = Set::filter(explode('.', $field), true);
  543. }
  544. foreach ($this->_unlockedFields as $unlockField) {
  545. $unlockParts = explode('.', $unlockField);
  546. if (array_values(array_intersect($field, $unlockParts)) === $unlockParts) {
  547. return;
  548. }
  549. }
  550. $last = end($field);
  551. if (is_numeric($last) || empty($last)) {
  552. array_pop($field);
  553. }
  554. $field = implode('.', $field);
  555. if ($lock) {
  556. if (!in_array($field, $this->fields)) {
  557. if ($value !== null) {
  558. return $this->fields[$field] = $value;
  559. }
  560. $this->fields[] = $field;
  561. }
  562. } else {
  563. $this->unlockField($field);
  564. }
  565. }
  566. /**
  567. * Returns true if there is an error for the given field, otherwise false
  568. *
  569. * @param string $field This should be "Modelname.fieldname"
  570. * @return boolean If there are errors this method returns true, else false.
  571. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::isFieldError
  572. */
  573. public function isFieldError($field) {
  574. $this->setEntity($field);
  575. return (bool)$this->tagIsInvalid();
  576. }
  577. /**
  578. * Returns a formatted error message for given FORM field, NULL if no errors.
  579. *
  580. * ### Options:
  581. *
  582. * - `escape` bool Whether or not to html escape the contents of the error.
  583. * - `wrap` mixed Whether or not the error message should be wrapped in a div. If a
  584. * string, will be used as the HTML tag to use.
  585. * - `class` string The classname for the error message
  586. *
  587. * @param string $field A field name, like "Modelname.fieldname"
  588. * @param mixed $text Error message as string or array of messages.
  589. * If array contains `attributes` key it will be used as options for error container
  590. * @param array $options Rendering options for <div /> wrapper tag
  591. * @return string If there are errors this method returns an error message, otherwise null.
  592. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::error
  593. */
  594. public function error($field, $text = null, $options = array()) {
  595. $defaults = array('wrap' => true, 'class' => 'error-message', 'escape' => true);
  596. $options = array_merge($defaults, $options);
  597. $this->setEntity($field);
  598. $error = $this->tagIsInvalid();
  599. if ($error === false) {
  600. return null;
  601. }
  602. if (is_array($text)) {
  603. if (isset($text['attributes']) && is_array($text['attributes'])) {
  604. $options = array_merge($options, $text['attributes']);
  605. unset($text['attributes']);
  606. }
  607. $tmp = array();
  608. foreach ($error as &$e) {
  609. if (isset($text[$e])) {
  610. $tmp []= $text[$e];
  611. } else {
  612. $tmp []= $e;
  613. }
  614. }
  615. $text = $tmp;
  616. }
  617. if ($text !== null) {
  618. $error = $text;
  619. }
  620. if (is_array($error)) {
  621. foreach ($error as &$e) {
  622. if (is_numeric($e)) {
  623. $e = __d('cake', 'Error in field %s', Inflector::humanize($this->field()));
  624. }
  625. }
  626. }
  627. if ($options['escape']) {
  628. $error = h($error);
  629. unset($options['escape']);
  630. }
  631. if (is_array($error)) {
  632. if (count($error) > 1) {
  633. $listParams = array();
  634. if (isset($options['listOptions'])) {
  635. if (is_string($options['listOptions'])) {
  636. $listParams []= $options['listOptions'];
  637. } else {
  638. if (isset($options['listOptions']['itemOptions'])) {
  639. $listParams []= $options['listOptions']['itemOptions'];
  640. unset($options['listOptions']['itemOptions']);
  641. } else {
  642. $listParams []= array();
  643. }
  644. if (isset($options['listOptions']['tag'])) {
  645. $listParams []= $options['listOptions']['tag'];
  646. unset($options['listOptions']['tag']);
  647. }
  648. array_unshift($listParams, $options['listOptions']);
  649. }
  650. unset($options['listOptions']);
  651. }
  652. array_unshift($listParams, $error);
  653. $error = call_user_func_array(array($this->Html, 'nestedList'), $listParams);
  654. } else {
  655. $error = array_pop($error);
  656. }
  657. }
  658. if ($options['wrap']) {
  659. $tag = is_string($options['wrap']) ? $options['wrap'] : 'div';
  660. unset($options['wrap']);
  661. return $this->Html->tag($tag, $error, $options);
  662. } else {
  663. return $error;
  664. }
  665. }
  666. /**
  667. * Returns a formatted LABEL element for HTML FORMs. Will automatically generate
  668. * a for attribute if one is not provided.
  669. *
  670. * @param string $fieldName This should be "Modelname.fieldname"
  671. * @param string $text Text that will appear in the label field.
  672. * @param mixed $options An array of HTML attributes, or a string, to be used as a class name.
  673. * @return string The formatted LABEL element
  674. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::label
  675. */
  676. public function label($fieldName = null, $text = null, $options = array()) {
  677. if (empty($fieldName)) {
  678. $fieldName = implode('.', $this->entity());
  679. }
  680. if ($text === null) {
  681. if (strpos($fieldName, '.') !== false) {
  682. $fieldElements = explode('.', $fieldName);
  683. $text = array_pop($fieldElements);
  684. } else {
  685. $text = $fieldName;
  686. }
  687. if (substr($text, -3) == '_id') {
  688. $text = substr($text, 0, strlen($text) - 3);
  689. }
  690. $text = __(Inflector::humanize(Inflector::underscore($text)));
  691. }
  692. if (is_string($options)) {
  693. $options = array('class' => $options);
  694. }
  695. if (isset($options['for'])) {
  696. $labelFor = $options['for'];
  697. unset($options['for']);
  698. } else {
  699. $labelFor = $this->domId($fieldName);
  700. }
  701. return $this->Html->useTag('label', $labelFor, $options, $text);
  702. }
  703. /**
  704. * Generate a set of inputs for `$fields`. If $fields is null the current model
  705. * will be used.
  706. *
  707. * In addition to controller fields output, `$fields` can be used to control legend
  708. * and fieldset rendering with the `fieldset` and `legend` keys.
  709. * `$form->inputs(array('legend' => 'My legend'));` Would generate an input set with
  710. * a custom legend. You can customize individual inputs through `$fields` as well.
  711. *
  712. * {{{
  713. * $form->inputs(array(
  714. * 'name' => array('label' => 'custom label')
  715. * ));
  716. * }}}
  717. *
  718. * In addition to fields control, inputs() allows you to use a few additional options.
  719. *
  720. * - `fieldset` Set to false to disable the fieldset. If a string is supplied it will be used as
  721. * the classname for the fieldset element.
  722. * - `legend` Set to false to disable the legend for the generated input set. Or supply a string
  723. * to customize the legend text.
  724. *
  725. * @param mixed $fields An array of fields to generate inputs for, or null.
  726. * @param array $blacklist a simple array of fields to not create inputs for.
  727. * @return string Completed form inputs.
  728. */
  729. public function inputs($fields = null, $blacklist = null) {
  730. $fieldset = $legend = true;
  731. $model = $this->model();
  732. if (is_array($fields)) {
  733. if (array_key_exists('legend', $fields)) {
  734. $legend = $fields['legend'];
  735. unset($fields['legend']);
  736. }
  737. if (isset($fields['fieldset'])) {
  738. $fieldset = $fields['fieldset'];
  739. unset($fields['fieldset']);
  740. }
  741. } elseif ($fields !== null) {
  742. $fieldset = $legend = $fields;
  743. if (!is_bool($fieldset)) {
  744. $fieldset = true;
  745. }
  746. $fields = array();
  747. }
  748. if (empty($fields)) {
  749. $fields = array_keys($this->_introspectModel($model, 'fields'));
  750. }
  751. if ($legend === true) {
  752. $actionName = __d('cake', 'New %s');
  753. $isEdit = (
  754. strpos($this->request->params['action'], 'update') !== false ||
  755. strpos($this->request->params['action'], 'edit') !== false
  756. );
  757. if ($isEdit) {
  758. $actionName = __d('cake', 'Edit %s');
  759. }
  760. $modelName = Inflector::humanize(Inflector::underscore($model));
  761. $legend = sprintf($actionName, __($modelName));
  762. }
  763. $out = null;
  764. foreach ($fields as $name => $options) {
  765. if (is_numeric($name) && !is_array($options)) {
  766. $name = $options;
  767. $options = array();
  768. }
  769. $entity = explode('.', $name);
  770. $blacklisted = (
  771. is_array($blacklist) &&
  772. (in_array($name, $blacklist) || in_array(end($entity), $blacklist))
  773. );
  774. if ($blacklisted) {
  775. continue;
  776. }
  777. $out .= $this->input($name, $options);
  778. }
  779. if (is_string($fieldset)) {
  780. $fieldsetClass = sprintf(' class="%s"', $fieldset);
  781. } else {
  782. $fieldsetClass = '';
  783. }
  784. if ($fieldset && $legend) {
  785. return $this->Html->useTag('fieldset', $fieldsetClass, $this->Html->useTag('legend', $legend) . $out);
  786. } elseif ($fieldset) {
  787. return $this->Html->useTag('fieldset', $fieldsetClass, $out);
  788. } else {
  789. return $out;
  790. }
  791. }
  792. /**
  793. * Generates a form input element complete with label and wrapper div
  794. *
  795. * ### Options
  796. *
  797. * See each field type method for more information. Any options that are part of
  798. * $attributes or $options for the different **type** methods can be included in `$options` for input().i
  799. * Additionally, any unknown keys that are not in the list below, or part of the selected type's options
  800. * will be treated as a regular html attribute for the generated input.
  801. *
  802. * - `type` - Force the type of widget you want. e.g. `type => 'select'`
  803. * - `label` - Either a string label, or an array of options for the label. See FormHelper::label()
  804. * - `div` - Either `false` to disable the div, or an array of options for the div.
  805. * See HtmlHelper::div() for more options.
  806. * - `options` - for widgets that take options e.g. radio, select
  807. * - `error` - control the error message that is produced
  808. * - `empty` - String or boolean to enable empty select box options.
  809. * - `before` - Content to place before the label + input.
  810. * - `after` - Content to place after the label + input.
  811. * - `between` - Content to place between the label + input.
  812. * - `format` - format template for element order. Any element that is not in the array, will not be in the output.
  813. * - Default input format order: array('before', 'label', 'between', 'input', 'after', 'error')
  814. * - Default checkbox format order: array('before', 'input', 'between', 'label', 'after', 'error')
  815. * - Hidden input will not be formatted
  816. * - Radio buttons cannot have the order of input and label elements controlled with these settings.
  817. *
  818. * @param string $fieldName This should be "Modelname.fieldname"
  819. * @param array $options Each type of input takes different options.
  820. * @return string Completed form widget.
  821. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#creating-form-elements
  822. */
  823. public function input($fieldName, $options = array()) {
  824. $this->setEntity($fieldName);
  825. $options = array_merge(
  826. array('before' => null, 'between' => null, 'after' => null, 'format' => null),
  827. $this->_inputDefaults,
  828. $options
  829. );
  830. $modelKey = $this->model();
  831. $fieldKey = $this->field();
  832. if (!isset($options['type'])) {
  833. $magicType = true;
  834. $options['type'] = 'text';
  835. if (isset($options['options'])) {
  836. $options['type'] = 'select';
  837. } elseif (in_array($fieldKey, array('psword', 'passwd', 'password'))) {
  838. $options['type'] = 'password';
  839. } elseif (isset($options['checked'])) {
  840. $options['type'] = 'checkbox';
  841. } elseif ($fieldDef = $this->_introspectModel($modelKey, 'fields', $fieldKey)) {
  842. $type = $fieldDef['type'];
  843. $primaryKey = $this->fieldset[$modelKey]['key'];
  844. }
  845. if (isset($type)) {
  846. $map = array(
  847. 'string' => 'text', 'datetime' => 'datetime',
  848. 'boolean' => 'checkbox', 'timestamp' => 'datetime',
  849. 'text' => 'textarea', 'time' => 'time',
  850. 'date' => 'date', 'float' => 'number',
  851. 'integer' => 'number'
  852. );
  853. if (isset($this->map[$type])) {
  854. $options['type'] = $this->map[$type];
  855. } elseif (isset($map[$type])) {
  856. $options['type'] = $map[$type];
  857. }
  858. if ($fieldKey == $primaryKey) {
  859. $options['type'] = 'hidden';
  860. }
  861. if (
  862. $options['type'] === 'number' &&
  863. $type === 'float' &&
  864. !isset($options['step'])
  865. ) {
  866. $options['step'] = 'any';
  867. }
  868. }
  869. if (preg_match('/_id$/', $fieldKey) && $options['type'] !== 'hidden') {
  870. $options['type'] = 'select';
  871. }
  872. if ($modelKey === $fieldKey) {
  873. $options['type'] = 'select';
  874. if (!isset($options['multiple'])) {
  875. $options['multiple'] = 'multiple';
  876. }
  877. }
  878. }
  879. $types = array('checkbox', 'radio', 'select');
  880. if (
  881. (!isset($options['options']) && in_array($options['type'], $types)) ||
  882. (isset($magicType) && $options['type'] == 'text')
  883. ) {
  884. $varName = Inflector::variable(
  885. Inflector::pluralize(preg_replace('/_id$/', '', $fieldKey))
  886. );
  887. $varOptions = $this->_View->getVar($varName);
  888. if (is_array($varOptions)) {
  889. if ($options['type'] !== 'radio') {
  890. $options['type'] = 'select';
  891. }
  892. $options['options'] = $varOptions;
  893. }
  894. }
  895. $autoLength = (!array_key_exists('maxlength', $options) && isset($fieldDef['length']));
  896. if ($autoLength && $options['type'] == 'text') {
  897. $options['maxlength'] = $fieldDef['length'];
  898. }
  899. if ($autoLength && $fieldDef['type'] == 'float') {
  900. $options['maxlength'] = array_sum(explode(',', $fieldDef['length']))+1;
  901. }
  902. $divOptions = array();
  903. $div = $this->_extractOption('div', $options, true);
  904. unset($options['div']);
  905. if (!empty($div)) {
  906. $divOptions['class'] = 'input';
  907. $divOptions = $this->addClass($divOptions, $options['type']);
  908. if (is_string($div)) {
  909. $divOptions['class'] = $div;
  910. } elseif (is_array($div)) {
  911. $divOptions = array_merge($divOptions, $div);
  912. }
  913. if ($this->_introspectModel($modelKey, 'validates', $fieldKey)) {
  914. $divOptions = $this->addClass($divOptions, 'required');
  915. }
  916. if (!isset($divOptions['tag'])) {
  917. $divOptions['tag'] = 'div';
  918. }
  919. }
  920. $label = null;
  921. if (isset($options['label']) && $options['type'] !== 'radio') {
  922. $label = $options['label'];
  923. unset($options['label']);
  924. }
  925. if ($options['type'] === 'radio') {
  926. $label = false;
  927. if (isset($options['options'])) {
  928. $radioOptions = (array)$options['options'];
  929. unset($options['options']);
  930. }
  931. }
  932. if ($label !== false) {
  933. $label = $this->_inputLabel($fieldName, $label, $options);
  934. }
  935. $error = $this->_extractOption('error', $options, null);
  936. unset($options['error']);
  937. $selected = $this->_extractOption('selected', $options, null);
  938. unset($options['selected']);
  939. if (isset($options['rows']) || isset($options['cols'])) {
  940. $options['type'] = 'textarea';
  941. }
  942. if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time' || $options['type'] === 'select') {
  943. $options += array('empty' => false);
  944. }
  945. if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time') {
  946. $dateFormat = $this->_extractOption('dateFormat', $options, 'MDY');
  947. $timeFormat = $this->_extractOption('timeFormat', $options, 12);
  948. unset($options['dateFormat'], $options['timeFormat']);
  949. }
  950. $type = $options['type'];
  951. $out = array_merge(
  952. array('before' => null, 'label' => null, 'between' => null, 'input' => null, 'after' => null, 'error' => null),
  953. array('before' => $options['before'], 'label' => $label, 'between' => $options['between'], 'after' => $options['after'])
  954. );
  955. $format = null;
  956. if (is_array($options['format']) && in_array('input', $options['format'])) {
  957. $format = $options['format'];
  958. }
  959. unset($options['type'], $options['before'], $options['between'], $options['after'], $options['format']);
  960. switch ($type) {
  961. case 'hidden':
  962. $input = $this->hidden($fieldName, $options);
  963. $format = array('input');
  964. unset($divOptions);
  965. break;
  966. case 'checkbox':
  967. $input = $this->checkbox($fieldName, $options);
  968. $format = $format ? $format : array('before', 'input', 'between', 'label', 'after', 'error');
  969. break;
  970. case 'radio':
  971. $input = $this->radio($fieldName, $radioOptions, $options);
  972. break;
  973. case 'file':
  974. $input = $this->file($fieldName, $options);
  975. break;
  976. case 'select':
  977. $options += array('options' => array(), 'value' => $selected);
  978. $list = $options['options'];
  979. unset($options['options']);
  980. $input = $this->select($fieldName, $list, $options);
  981. break;
  982. case 'time':
  983. $options['value'] = $selected;
  984. $input = $this->dateTime($fieldName, null, $timeFormat, $options);
  985. break;
  986. case 'date':
  987. $options['value'] = $selected;
  988. $input = $this->dateTime($fieldName, $dateFormat, null, $options);
  989. break;
  990. case 'datetime':
  991. $options['value'] = $selected;
  992. $input = $this->dateTime($fieldName, $dateFormat, $timeFormat, $options);
  993. break;
  994. case 'textarea':
  995. $input = $this->textarea($fieldName, $options + array('cols' => '30', 'rows' => '6'));
  996. break;
  997. case 'url':
  998. $input = $this->text($fieldName, array('type' => 'url') + $options);
  999. break;
  1000. default:
  1001. $input = $this->{$type}($fieldName, $options);
  1002. }
  1003. if ($type != 'hidden' && $error !== false) {
  1004. $errMsg = $this->error($fieldName, $error);
  1005. if ($errMsg) {
  1006. $divOptions = $this->addClass($divOptions, 'error');
  1007. $out['error'] = $errMsg;
  1008. }
  1009. }
  1010. $out['input'] = $input;
  1011. $format = $format ? $format : array('before', 'label', 'between', 'input', 'after', 'error');
  1012. $output = '';
  1013. foreach ($format as $element) {
  1014. $output .= $out[$element];
  1015. unset($out[$element]);
  1016. }
  1017. if (!empty($divOptions['tag'])) {
  1018. $tag = $divOptions['tag'];
  1019. unset($divOptions['tag']);
  1020. $output = $this->Html->tag($tag, $output, $divOptions);
  1021. }
  1022. return $output;
  1023. }
  1024. /**
  1025. * Extracts a single option from an options array.
  1026. *
  1027. * @param string $name The name of the option to pull out.
  1028. * @param array $options The array of options you want to extract.
  1029. * @param mixed $default The default option value
  1030. * @return mixed the contents of the option or default
  1031. */
  1032. protected function _extractOption($name, $options, $default = null) {
  1033. if (array_key_exists($name, $options)) {
  1034. return $options[$name];
  1035. }
  1036. return $default;
  1037. }
  1038. /**
  1039. * Generate a label for an input() call.
  1040. *
  1041. * @param string $fieldName
  1042. * @param string $label
  1043. * @param array $options Options for the label element.
  1044. * @return string Generated label element
  1045. */
  1046. protected function _inputLabel($fieldName, $label, $options) {
  1047. $labelAttributes = $this->domId(array(), 'for');
  1048. if ($options['type'] === 'date' || $options['type'] === 'datetime') {
  1049. if (isset($options['dateFormat']) && $options['dateFormat'] === 'NONE') {
  1050. $labelAttributes['for'] .= 'Hour';
  1051. $idKey = 'hour';
  1052. } else {
  1053. $labelAttributes['for'] .= 'Month';
  1054. $idKey = 'month';
  1055. }
  1056. if (isset($options['id']) && isset($options['id'][$idKey])) {
  1057. $labelAttributes['for'] = $options['id'][$idKey];
  1058. }
  1059. } elseif ($options['type'] === 'time') {
  1060. $labelAttributes['for'] .= 'Hour';
  1061. if (isset($options['id']) && isset($options['id']['hour'])) {
  1062. $labelAttributes['for'] = $options['id']['hour'];
  1063. }
  1064. }
  1065. if (is_array($label)) {
  1066. $labelText = null;
  1067. if (isset($label['text'])) {
  1068. $labelText = $label['text'];
  1069. unset($label['text']);
  1070. }
  1071. $labelAttributes = array_merge($labelAttributes, $label);
  1072. } else {
  1073. $labelText = $label;
  1074. }
  1075. if (isset($options['id']) && is_string($options['id'])) {
  1076. $labelAttributes = array_merge($labelAttributes, array('for' => $options['id']));
  1077. }
  1078. return $this->label($fieldName, $labelText, $labelAttributes);
  1079. }
  1080. /**
  1081. * Creates a checkbox input widget.
  1082. *
  1083. * ### Options:
  1084. *
  1085. * - `value` - the value of the checkbox
  1086. * - `checked` - boolean indicate that this checkbox is checked.
  1087. * - `hiddenField` - boolean to indicate if you want the results of checkbox() to include
  1088. * a hidden input with a value of ''.
  1089. * - `disabled` - create a disabled input.
  1090. * - `default` - Set the default value for the checkbox. This allows you to start checkboxes
  1091. * as checked, without having to check the POST data. A matching POST data value, will overwrite
  1092. * the default value.
  1093. *
  1094. * @param string $fieldName Name of a field, like this "Modelname.fieldname"
  1095. * @param array $options Array of HTML attributes.
  1096. * @return string An HTML text input element.
  1097. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
  1098. */
  1099. public function checkbox($fieldName, $options = array()) {
  1100. $valueOptions = array();
  1101. if(isset($options['default'])){
  1102. $valueOptions['default'] = $options['default'];
  1103. unset($options['default']);
  1104. }
  1105. $options = $this->_initInputField($fieldName, $options) + array('hiddenField' => true);
  1106. $value = current($this->value($valueOptions));
  1107. $output = "";
  1108. if (empty($options['value'])) {
  1109. $options['value'] = 1;
  1110. }
  1111. if (
  1112. (!isset($options['checked']) && !empty($value) && $value == $options['value']) ||
  1113. !empty($options['checked'])
  1114. ) {
  1115. $options['checked'] = 'checked';
  1116. }
  1117. if ($options['hiddenField']) {
  1118. $hiddenOptions = array(
  1119. 'id' => $options['id'] . '_', 'name' => $options['name'],
  1120. 'value' => '0', 'secure' => false
  1121. );
  1122. if (isset($options['disabled']) && $options['disabled'] == true) {
  1123. $hiddenOptions['disabled'] = 'disabled';
  1124. }
  1125. $output = $this->hidden($fieldName, $hiddenOptions);
  1126. }
  1127. unset($options['hiddenField']);
  1128. return $output . $this->Html->useTag('checkbox', $options['name'], array_diff_key($options, array('name' => '')));
  1129. }
  1130. /**
  1131. * Creates a set of radio widgets. Will create a legend and fieldset
  1132. * by default. Use $options to control this
  1133. *
  1134. * ### Attributes:
  1135. *
  1136. * - `separator` - define the string in between the radio buttons
  1137. * - `legend` - control whether or not the widget set has a fieldset & legend
  1138. * - `value` - indicate a value that is should be checked
  1139. * - `label` - boolean to indicate whether or not labels for widgets show be displayed
  1140. * - `hiddenField` - boolean to indicate if you want the results of radio() to include
  1141. * a hidden input with a value of ''. This is useful for creating radio sets that non-continuous
  1142. *
  1143. * @param string $fieldName Name of a field, like this "Modelname.fieldname"
  1144. * @param array $options Radio button options array.
  1145. * @param array $attributes Array of HTML attributes, and special attributes above.
  1146. * @return string Completed radio widget set.
  1147. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
  1148. */
  1149. public function radio($fieldName, $options = array(), $attributes = array()) {
  1150. $attributes = $this->_initInputField($fieldName, $attributes);
  1151. $legend = false;
  1152. $disabled = array();
  1153. if (isset($attributes['legend'])) {
  1154. $legend = $attributes['legend'];
  1155. unset($attributes['legend']);
  1156. } elseif (count($options) > 1) {
  1157. $legend = __(Inflector::humanize($this->field()));
  1158. }
  1159. $label = true;
  1160. if (isset($attributes['label'])) {
  1161. $label = $attributes['label'];
  1162. unset($attributes['label']);
  1163. }
  1164. $inbetween = null;
  1165. if (isset($attributes['separator'])) {
  1166. $inbetween = $attributes['separator'];
  1167. unset($attributes['separator']);
  1168. }
  1169. if (isset($attributes['value'])) {
  1170. $value = $attributes['value'];
  1171. } else {
  1172. $value = $this->value($fieldName);
  1173. }
  1174. if (isset($attributes['disabled'])) {
  1175. $disabled = $attributes['disabled'];
  1176. }
  1177. $out = array();
  1178. $hiddenField = isset($attributes['hiddenField']) ? $attributes['hiddenField'] : true;
  1179. unset($attributes['hiddenField']);
  1180. foreach ($options as $optValue => $optTitle) {
  1181. $optionsHere = array('value' => $optValue);
  1182. if (isset($value) && $optValue == $value) {
  1183. $optionsHere['checked'] = 'checked';
  1184. }
  1185. if (!empty($disabled) && in_array($optValue, $disabled)) {
  1186. $optionsHere['disabled'] = true;
  1187. }
  1188. $tagName = Inflector::camelize(
  1189. $attributes['id'] . '_' . Inflector::slug($optValue)
  1190. );
  1191. if ($label) {
  1192. $optTitle = $this->Html->useTag('label', $tagName, '', $optTitle);
  1193. }
  1194. $allOptions = array_merge($attributes, $optionsHere);
  1195. $out[] = $this->Html->useTag('radio', $attributes['name'], $tagName,
  1196. array_diff_key($allOptions, array('name' => '', 'type' => '', 'id' => '')),
  1197. $optTitle
  1198. );
  1199. }
  1200. $hidden = null;
  1201. if ($hiddenField) {
  1202. if (!isset($value) || $value === '') {
  1203. $hidden = $this->hidden($fieldName, array(
  1204. 'id' => $attributes['id'] . '_', 'value' => '', 'name' => $attributes['name']
  1205. ));
  1206. }
  1207. }
  1208. $out = $hidden . implode($inbetween, $out);
  1209. if ($legend) {
  1210. $out = $this->Html->useTag('fieldset', '', $this->Html->useTag('legend', $legend) . $out);
  1211. }
  1212. return $out;
  1213. }
  1214. /**
  1215. * Missing method handler - implements various simple input types. Is used to create inputs
  1216. * of various types. e.g. `$this->Form->text();` will create `<input type="text" />` while
  1217. * `$this->Form->range();` will create `<input type="range" />`
  1218. *
  1219. * ### Usage
  1220. *
  1221. * `$this->Form->search('User.query', array('value' => 'test'));`
  1222. *
  1223. * Will make an input like:
  1224. *
  1225. * `<input type="search" id="UserQuery" name="data[User][query]" value="test" />`
  1226. *
  1227. * The first argument to an input type should always be the fieldname, in `Model.field` format.
  1228. * The second argument should always be an array of attributes for the input.
  1229. *
  1230. * @param string $method Method name / input type to make.
  1231. * @param array $params Parameters for the method call
  1232. * @return string Formatted input method.
  1233. * @throws CakeException When there are no params for the method call.
  1234. */
  1235. public function __call($method, $params) {
  1236. $options = array();
  1237. if (empty($params)) {
  1238. throw new CakeException(__d('cake_dev', 'Missing field name for FormHelper::%s', $method));
  1239. }
  1240. if (isset($params[1])) {
  1241. $options = $params[1];
  1242. }
  1243. if (!isset($options['type'])) {
  1244. $options['type'] = $method;
  1245. }
  1246. $options = $this->_initInputField($params[0], $options);
  1247. return $this->Html->useTag('input', $options['name'], array_diff_key($options, array('name' => '')));
  1248. }
  1249. /**
  1250. * Creates a textarea widget.
  1251. *
  1252. * ### Options:
  1253. *
  1254. * - `escape` - Whether or not the contents of the textarea should be escaped. Defaults to true.
  1255. *
  1256. * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
  1257. * @param array $options Array of HTML attributes, and special options above.
  1258. * @return string A generated HTML text input element
  1259. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::textarea
  1260. */
  1261. public function textarea($fieldName, $options = array()) {
  1262. $options = $this->_initInputField($fieldName, $options);
  1263. $value = null;
  1264. if (array_key_exists('value', $options)) {
  1265. $value = $options['value'];
  1266. if (!array_key_exists('escape', $options) || $options['escape'] !== false) {
  1267. $value = h($value);
  1268. }
  1269. unset($options['value']);
  1270. }
  1271. return $this->Html->useTag('textarea', $options['name'], array_diff_key($options, array('type' => '', 'name' => '')), $value);
  1272. }
  1273. /**
  1274. * Creates a hidden input field.
  1275. *
  1276. * @param string $fieldName Name of a field, in the form of "Modelname.fieldname"
  1277. * @param array $options Array of HTML attributes.
  1278. * @return string A generated hidden input
  1279. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hidden
  1280. */
  1281. public function hidden($fieldName, $options = array()) {
  1282. $secure = true;
  1283. if (isset($options['secure'])) {
  1284. $secure = $options['secure'];
  1285. unset($options['secure']);
  1286. }
  1287. $options = $this->_initInputField($fieldName, array_merge(
  1288. $options, array('secure' => self::SECURE_SKIP)
  1289. ));
  1290. if ($secure && $secure !== self::SECURE_SKIP) {
  1291. $this->_secure(true, null, '' . $options['value']);
  1292. }
  1293. return $this->Html->useTag('hidden', $options['name'], array_diff_key($options, array('name' => '')));
  1294. }
  1295. /**
  1296. * Creates file input widget.
  1297. *
  1298. * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
  1299. * @param array $options Array of HTML attributes.
  1300. * @return string A generated file input.
  1301. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::file
  1302. */
  1303. public function file($fieldName, $options = array()) {
  1304. $options += array('secure' => true);
  1305. $secure = $options['secure'];
  1306. $options['secure'] = self::SECURE_SKIP;
  1307. $options = $this->_initInputField($fieldName, $options);
  1308. $field = $this->entity();
  1309. foreach (array('name', 'type', 'tmp_name', 'error', 'size') as $suffix) {
  1310. $this->_secure($secure, array_merge($field, array($suffix)));
  1311. }
  1312. return $this->Html->useTag('file', $options['name'], array_diff_key($options, array('name' => '')));
  1313. }
  1314. /**
  1315. * Creates a `<button>` tag. The type attribute defaults to `type="submit"`
  1316. * You can change it to a different value by using `$options['type']`.
  1317. *
  1318. * ### Options:
  1319. *
  1320. * - `escape` - HTML entity encode the $title of the button. Defaults to false.
  1321. *
  1322. * @param string $title The button's caption. Not automatically HTML encoded
  1323. * @param array $options Array of options and HTML attributes.
  1324. * @return string A HTML button tag.
  1325. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::button
  1326. */
  1327. public function button($title, $options = array()) {
  1328. $options += array('type' => 'submit', 'escape' => false, 'secure' => false);
  1329. if ($options['escape']) {
  1330. $title = h($title);
  1331. }
  1332. if (isset($options['name'])) {
  1333. $this->_secure($options['secure'], $options['name']);
  1334. }
  1335. return $this->Html->useTag('button', $options['type'], array_diff_key($options, array('type' => '')), $title);
  1336. }
  1337. /**
  1338. * Create a `<button>` tag with a surrounding `<form>` that submits via POST.
  1339. *
  1340. * This method creates a `<form>` element. So do not use this method in some opened form.
  1341. * Instead use FormHelper::submit() or FormHelper::button() to create buttons inside opened forms.
  1342. *
  1343. * ### Options:
  1344. *
  1345. * - `data` - Array with key/value to pass in input hidden
  1346. * - Other options is the same of button method.
  1347. *
  1348. * @param string $title The button's caption. Not automatically HTML encoded
  1349. * @param mixed $url URL as string or array
  1350. * @param array $options Array of options and HTML attributes.
  1351. * @return string A HTML button tag.
  1352. */
  1353. public function postButton($title, $url, $options = array()) {
  1354. $out = $this->create(false, array('id' => false, 'url' => $url, 'style' => 'display:none;'));
  1355. if (isset($options['data']) && is_array($options['data'])) {
  1356. foreach ($options['data'] as $key => $value) {
  1357. $out .= $this->hidden($key, array('value' => $value, 'id' => false));
  1358. }
  1359. unset($options['data']);
  1360. }
  1361. $out .= $this->button($title, $options);
  1362. $out .= $this->end();
  1363. return $out;
  1364. }
  1365. /**
  1366. * Creates an HTML link, but access the url using method POST.
  1367. * Requires javascript to be enabled in browser.
  1368. *
  1369. * This method creates a `<form>` element. So do not use this method inside an existing form.
  1370. * Instead you should add a submit button using FormHelper::submit()
  1371. *
  1372. * ### Options:
  1373. *
  1374. * - `data` - Array with key/value to pass in input hidden
  1375. * - `confirm` - Can be used instead of $confirmMessage.
  1376. * - Other options is the same of HtmlHelper::link() method.
  1377. * - The option `onclick` will be replaced.
  1378. *
  1379. * @param string $title The content to be wrapped by <a> tags.
  1380. * @param mixed $url Cake-relative URL or array of URL parameters, or external URL (starts with http://)
  1381. * @param array $options Array of HTML attributes.
  1382. * @param string $confirmMessage JavaScript confirmation message.
  1383. * @return string An `<a />` element.
  1384. */
  1385. public function postLink($title, $url = null, $options = array(), $confirmMessage = false) {
  1386. if (!empty($options['confirm'])) {
  1387. $confirmMessage = $options['confirm'];
  1388. unset($options['confirm']);
  1389. }
  1390. $formName = uniqid('post_');
  1391. $formUrl = $this->url($url);
  1392. $out = $this->Html->useTag('form', $formUrl, array('name' => $formName, 'id' => $formName, 'style' => 'display:none;', 'method' => 'post'));
  1393. $out .= $this->Html->useTag('hidden', '_method', ' value="POST"');
  1394. $out .= $this->_csrfField();
  1395. $fields = array();
  1396. if (isset($options['data']) && is_array($options['data'])) {
  1397. foreach ($options['data'] as $key => $value) {
  1398. $fields[$key] = $value;
  1399. $out .= $this->hidden($key, array('value' => $value, 'id' => false));
  1400. }
  1401. unset($options['data']);
  1402. }
  1403. $out .= $this->secure($fields);
  1404. $out .= $this->Html->useTag('formend');
  1405. $url = '#';
  1406. $onClick = 'document.' . $formName . '.submit();';
  1407. if ($confirmMessage) {
  1408. $confirmMessage = str_replace(array("'", '"'), array("\'", '\"'), $confirmMessage);
  1409. $options['onclick'] = "if (confirm('{$confirmMessage}')) { {$onClick} }";
  1410. } else {
  1411. $options['onclick'] = $onClick;
  1412. }
  1413. $options['onclick'] .= ' event.returnValue = false; return false;';
  1414. $out .= $this->Html->link($title, $url, $options);
  1415. return $out;
  1416. }
  1417. /**
  1418. * Creates a submit button element. This method will generate `<input />` elements that
  1419. * can be used to submit, and reset forms by using $options. image submits can be created by supplying an
  1420. * image path for $caption.
  1421. *
  1422. * ### Options
  1423. *
  1424. * - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to
  1425. * FormHelper::input().
  1426. * - `before` - Content to include before the input.
  1427. * - `after` - Content to include after the input.
  1428. * - `type` - Set to 'reset' for reset inputs. Defaults to 'submit'
  1429. * - Other attributes will be assigned to the input element.
  1430. *
  1431. * ### Options
  1432. *
  1433. * - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to
  1434. * FormHelper::input().
  1435. * - Other attributes will be assigned to the input element.
  1436. *
  1437. * @param string $caption The label appearing on the button OR if string contains :// or the
  1438. * extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension
  1439. * exists, AND the first character is /, image is relative to webroot,
  1440. * OR if the first character is not /, image is relative to webroot/img.
  1441. * @param array $options Array of options. See above.
  1442. * @return string A HTML submit button
  1443. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::submit
  1444. */
  1445. public function submit($caption = null, $options = array()) {
  1446. if (!is_string($caption) && empty($caption)) {
  1447. $caption = __d('cake', 'Submit');
  1448. }
  1449. $out = null;
  1450. $div = true;
  1451. if (isset($options['div'])) {
  1452. $div = $options['div'];
  1453. unset($options['div']);
  1454. }
  1455. $options += array('type' => 'submit', 'before' => null, 'after' => null, 'secure' => false);
  1456. $divOptions = array('tag' => 'div');
  1457. if ($div === true) {
  1458. $divOptions['class'] = 'submit';
  1459. } elseif ($div === false) {
  1460. unset($divOptions);
  1461. } elseif (is_string($div)) {
  1462. $divOptions['class'] = $div;
  1463. } elseif (is_array($div)) {
  1464. $divOptions = array_merge(array('class' => 'submit', 'tag' => 'div'), $div);
  1465. }
  1466. if (isset($options['name'])) {
  1467. $this->_secure($options['secure'], $options['name']);
  1468. }
  1469. unset($options['secure']);
  1470. $before = $options['before'];
  1471. $after = $options['after'];
  1472. unset($options['before'], $options['after']);
  1473. $isUrl = strpos($caption, '://') !== false;
  1474. $isImage = preg_match('/\.(jpg|jpe|jpeg|gif|png|ico)$/', $caption);
  1475. if ($isUrl || $isImage) {
  1476. $unlockFields = array('x', 'y');
  1477. if (isset($options['name'])) {
  1478. $unlockFields = array(
  1479. $options['name'] . '_x', $options['name'] . '_y'
  1480. );
  1481. }
  1482. foreach ($unlockFields as $ignore) {
  1483. $this->unlockField($ignore);
  1484. }
  1485. }
  1486. if ($isUrl) {
  1487. unset($options['type']);
  1488. $tag = $this->Html->useTag('submitimage', $caption, $options);
  1489. } elseif ($isImage) {
  1490. unset($options['type']);
  1491. if ($caption{0} !== '/') {
  1492. $url = $this->webroot(IMAGES_URL . $caption);
  1493. } else {
  1494. $url = $this->webroot(trim($caption, '/'));
  1495. }
  1496. $url = $this->assetTimestamp($url);
  1497. $tag = $this->Html->useTag('submitimage', $url, $options);
  1498. } else {
  1499. $options['value'] = $caption;
  1500. $tag = $this->Html->useTag('submit', $options);
  1501. }
  1502. $out = $before . $tag . $after;
  1503. if (isset($divOptions)) {
  1504. $tag = $divOptions['tag'];
  1505. unset($divOptions['tag']);
  1506. $out = $this->Html->tag($tag, $out, $divOptions);
  1507. }
  1508. return $out;
  1509. }
  1510. /**
  1511. * Returns a formatted SELECT element.
  1512. *
  1513. * ### Attributes:
  1514. *
  1515. * - `showParents` - If included in the array and set to true, an additional option element
  1516. * will be added for the parent of each option group. You can set an option with the same name
  1517. * and it's key will be used for the value of the option.
  1518. * - `multiple` - show a multiple select box. If set to 'checkbox' multiple checkboxes will be
  1519. * created instead.
  1520. * - `empty` - If true, the empty select option is shown. If a string,
  1521. * that string is displayed as the empty element.
  1522. * - `escape` - If true contents of options will be HTML entity encoded. Defaults to true.
  1523. * - `value` The selected value of the input.
  1524. * - `class` - When using multiple = checkbox the classname to apply to the divs. Defaults to 'checkbox'.
  1525. *
  1526. * ### Using options
  1527. *
  1528. * A simple array will create normal options:
  1529. *
  1530. * {{{
  1531. * $options = array(1 => 'one', 2 => 'two);
  1532. * $this->Form->select('Model.field', $options));
  1533. * }}}
  1534. *
  1535. * While a nested options array will create optgroups with options inside them.
  1536. * {{{
  1537. * $options = array(
  1538. * 1 => 'bill',
  1539. * 'fred' => array(
  1540. * 2 => 'fred',
  1541. * 3 => 'fred jr.'
  1542. * )
  1543. * );
  1544. * $this->Form->select('Model.field', $options);
  1545. * }}}
  1546. *
  1547. * In the above `2 => 'fred'` will not generate an option element. You should enable the `showParents`
  1548. * attribute to show the fred option.
  1549. *
  1550. * If you have multiple options that need to have the same value attribute, you can
  1551. * use an array of arrays to express this:
  1552. *
  1553. * {{{
  1554. * $options = array(
  1555. * array('name' => 'United states', 'value' => 'USA'),
  1556. * array('name' => 'USA', 'value' => 'USA'),
  1557. * );
  1558. * }}}
  1559. *
  1560. * @param string $fieldName Name attribute of the SELECT
  1561. * @param array $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the
  1562. * SELECT element
  1563. * @param array $attributes The HTML attributes of the select element.
  1564. * @return string Formatted SELECT element
  1565. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
  1566. */
  1567. public function select($fieldName, $options = array(), $attributes = array()) {
  1568. $select = array();
  1569. $style = null;
  1570. $tag = null;
  1571. $attributes += array(
  1572. 'class' => null,
  1573. 'escape' => true,
  1574. 'secure' => true,
  1575. 'empty' => '',
  1576. 'showParents' => false,
  1577. 'hiddenField' => true
  1578. );
  1579. $escapeOptions = $this->_extractOption('escape', $attributes);
  1580. $secure = $this->_extractOption('secure', $attributes);
  1581. $showEmpty = $this->_extractOption('empty', $attributes);
  1582. $showParents = $this->_extractOption('showParents', $attributes);
  1583. $hiddenField = $this->_extractOption('hiddenField', $attributes);
  1584. unset($attributes['escape'], $attributes['secure'], $attributes['empty'], $attributes['showParents'], $attributes['hiddenField']);
  1585. $id = $this->_extractOption('id', $attributes);
  1586. $attributes = $this->_initInputField($fieldName, array_merge(
  1587. (array)$attributes, array('secure' => self::SECURE_SKIP)
  1588. ));
  1589. if (is_string($options) && isset($this->_options[$options])) {
  1590. $options = $this->_generateOptions($options);
  1591. } elseif (!is_array($options)) {
  1592. $options = array();
  1593. }
  1594. if (isset($attributes['type'])) {
  1595. unset($attributes['type']);
  1596. }
  1597. if (!isset($selected)) {
  1598. $selected = $attributes['value'];
  1599. }
  1600. if (!empty($attributes['multiple'])) {
  1601. $style = ($attributes['multiple'] === 'checkbox') ? 'checkbox' : null;
  1602. $template = ($style) ? 'checkboxmultiplestart' : 'selectmultiplestart';
  1603. $tag = $template;
  1604. if ($hiddenField) {
  1605. $hiddenAttributes = array(
  1606. 'value' => '',
  1607. 'id' => $attributes['id'] . ($style ? '' : '_'),
  1608. 'secure' => false,
  1609. 'name' => $attributes['name']
  1610. );
  1611. $select[] = $this->hidden(null, $hiddenAttributes);
  1612. }
  1613. } else {
  1614. $tag = 'selectstart';
  1615. }
  1616. if (!empty($tag) || isset($template)) {
  1617. if (!isset($secure) || $secure == true) {
  1618. $this->_secure(true);
  1619. }
  1620. $select[] = $this->Html->useTag($tag, $attributes['name'], array_diff_key($attributes, array('name' => '', 'value' => '')));
  1621. }
  1622. $emptyMulti = (
  1623. $showEmpty !== null && $showEmpty !== false && !(
  1624. empty($showEmpty) && (isset($attributes) &&
  1625. array_key_exists('multiple', $attributes))
  1626. )
  1627. );
  1628. if ($emptyMulti) {
  1629. $showEmpty = ($showEmpty === true) ? '' : $showEmpty;
  1630. $options = array_reverse($options, true);
  1631. $options[''] = $showEmpty;
  1632. $options = array_reverse($options, true);
  1633. }
  1634. if (!$id) {
  1635. $attributes['id'] = Inflector::camelize($attributes['id']);
  1636. }
  1637. $select = array_merge($select, $this->_selectOptions(
  1638. array_reverse($options, true),
  1639. array(),
  1640. $showParents,
  1641. array(
  1642. 'escape' => $escapeOptions,
  1643. 'style' => $style,
  1644. 'name' => $attributes['name'],
  1645. 'value' => $attributes['value'],
  1646. 'class' => $attributes['class'],
  1647. 'id' => $attributes['id']
  1648. )
  1649. ));
  1650. $template = ($style == 'checkbox') ? 'checkboxmultipleend' : 'selectend';
  1651. $select[] = $this->Html->useTag($template);
  1652. return implode("\n", $select);
  1653. }
  1654. /**
  1655. * Returns a SELECT element for days.
  1656. *
  1657. * ### Attributes:
  1658. *
  1659. * - `empty` - If true, the empty select option is shown. If a string,
  1660. * that string is displayed as the empty element.
  1661. * - `value` The selected value of the input.
  1662. *
  1663. * @param string $fieldName Prefix name for the SELECT element
  1664. * @param array $attributes HTML attributes for the select element
  1665. * @return string A generated day select box.
  1666. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::day
  1667. */
  1668. public function day($fieldName = null, $attributes = array()) {
  1669. $attributes += array('empty' => true, 'value' => null);
  1670. $attributes = $this->_dateTimeSelected('day', $fieldName, $attributes);
  1671. if (strlen($attributes['value']) > 2) {
  1672. $attributes['value'] = date('d', strtotime($attributes['value']));
  1673. } elseif ($attributes['value'] === false) {
  1674. $attributes['value'] = null;
  1675. }
  1676. return $this->select($fieldName . ".day", $this->_generateOptions('day'), $attributes);
  1677. }
  1678. /**
  1679. * Returns a SELECT element for years
  1680. *
  1681. * ### Attributes:
  1682. *
  1683. * - `empty` - If true, the empty select option is shown. If a string,
  1684. * that string is displayed as the empty element.
  1685. * - `orderYear` - Ordering of year values in select options.
  1686. * Possible values 'asc', 'desc'. Default 'desc'
  1687. * - `value` The selected value of the input.
  1688. *
  1689. * @param string $fieldName Prefix name for the SELECT element
  1690. * @param integer $minYear First year in sequence
  1691. * @param integer $maxYear Last year in sequence
  1692. * @param array $attributes Attribute array for the select elements.
  1693. * @return string Completed year select input
  1694. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::year
  1695. */
  1696. public function year($fieldName, $minYear = null, $maxYear = null, $attributes = array()) {
  1697. $attributes += array('empty' => true, 'value' => null);
  1698. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  1699. if (is_array($value)) {
  1700. extract($value);
  1701. $attributes['value'] = $year;
  1702. } else {
  1703. if (empty($value)) {
  1704. if (!$attributes['empty'] && !$maxYear) {
  1705. $attributes['value'] = 'now';
  1706. } elseif (!$attributes['empty'] && $maxYear && !$attributes['value']) {
  1707. $attributes['value'] = $maxYear;
  1708. }
  1709. } else {
  1710. $attributes['value'] = $value;
  1711. }
  1712. }
  1713. }
  1714. if (strlen($attributes['value']) > 4 || $attributes['value'] === 'now') {
  1715. $attributes['value'] = date('Y', strtotime($attributes['value']));
  1716. } elseif ($attributes['value'] === false) {
  1717. $attributes['value'] = null;
  1718. }
  1719. $yearOptions = array('min' => $minYear, 'max' => $maxYear, 'order' => 'desc');
  1720. if (isset($attributes['orderYear'])) {
  1721. $yearOptions['order'] = $attributes['orderYear'];
  1722. unset($attributes['orderYear']);
  1723. }
  1724. return $this->select(
  1725. $fieldName . '.year', $this->_generateOptions('year', $yearOptions),
  1726. $attributes
  1727. );
  1728. }
  1729. /**
  1730. * Returns a SELECT element for months.
  1731. *
  1732. * ### Attributes:
  1733. *
  1734. * - `monthNames` - If false, 2 digit numbers will be used instead of text.
  1735. * If a array, the given array will be used.
  1736. * - `empty` - If true, the empty select option is shown. If a string,
  1737. * that string is displayed as the empty element.
  1738. * - `value` The selected value of the input.
  1739. *
  1740. * @param string $fieldName Prefix name for the SELECT element
  1741. * @param array $attributes Attributes for the select element
  1742. * @return string A generated month select dropdown.
  1743. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::month
  1744. */
  1745. public function month($fieldName, $attributes = array()) {
  1746. $attributes += array('empty' => true, 'value' => null);
  1747. $attributes = $this->_dateTimeSelected('month', $fieldName, $attributes);
  1748. if (strlen($attributes['value']) > 2) {
  1749. $attributes['value'] = date('m', strtotime($attributes['value']));
  1750. } elseif ($attributes['value'] === false) {
  1751. $attributes['value'] = null;
  1752. }
  1753. $defaults = array('monthNames' => true);
  1754. $attributes = array_merge($defaults, (array) $attributes);
  1755. $monthNames = $attributes['monthNames'];
  1756. unset($attributes['monthNames']);
  1757. return $this->select(
  1758. $fieldName . ".month",
  1759. $this->_generateOptions('month', array('monthNames' => $monthNames)),
  1760. $attributes
  1761. );
  1762. }
  1763. /**
  1764. * Returns a SELECT element for hours.
  1765. *
  1766. * ### Attributes:
  1767. *
  1768. * - `empty` - If true, the empty select option is shown. If a string,
  1769. * that string is displayed as the empty element.
  1770. * - `value` The selected value of the input.
  1771. *
  1772. * @param string $fieldName Prefix name for the SELECT element
  1773. * @param boolean $format24Hours True for 24 hours format
  1774. * @param array $attributes List of HTML attributes
  1775. * @return string Completed hour select input
  1776. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hour
  1777. */
  1778. public function hour($fieldName, $format24Hours = false, $attributes = array()) {
  1779. $attributes += array('empty' => true, 'value' => null);
  1780. $attributes = $this->_dateTimeSelected('hour', $fieldName, $attributes);
  1781. if (strlen($attributes['value']) > 2) {
  1782. if ($format24Hours) {
  1783. $attributes['value'] = date('H', strtotime($attributes['value']));
  1784. } else {
  1785. $attributes['value'] = date('g', strtotime($attributes['value']));
  1786. }
  1787. } elseif ($attributes['value'] === false) {
  1788. $attributes['value'] = null;
  1789. }
  1790. return $this->select(
  1791. $fieldName . ".hour",
  1792. $this->_generateOptions($format24Hours ? 'hour24' : 'hour'),
  1793. $attributes
  1794. );
  1795. }
  1796. /**
  1797. * Returns a SELECT element for minutes.
  1798. *
  1799. * ### Attributes:
  1800. *
  1801. * - `empty` - If true, the empty select option is shown. If a string,
  1802. * that string is displayed as the empty element.
  1803. * - `value` The selected value of the input.
  1804. *
  1805. * @param string $fieldName Prefix name for the SELECT element
  1806. * @param string $attributes Array of Attributes
  1807. * @return string Completed minute select input.
  1808. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::minute
  1809. */
  1810. public function minute($fieldName, $attributes = array()) {
  1811. $attributes += array('empty' => true, 'value' => null);
  1812. $attributes = $this->_dateTimeSelected('min', $fieldName, $attributes);
  1813. if (strlen($attributes['value']) > 2) {
  1814. $attributes['value'] = date('i', strtotime($attributes['value']));
  1815. } elseif ($attributes['value'] === false) {
  1816. $attributes['value'] = null;
  1817. }
  1818. $minuteOptions = array();
  1819. if (isset($attributes['interval'])) {
  1820. $minuteOptions['interval'] = $attributes['interval'];
  1821. unset($attributes['interval']);
  1822. }
  1823. return $this->select(
  1824. $fieldName . ".min", $this->_generateOptions('minute', $minuteOptions),
  1825. $attributes
  1826. );
  1827. }
  1828. /**
  1829. * Selects values for dateTime selects.
  1830. *
  1831. * @param string $select Name of element field. ex. 'day'
  1832. * @param string $fieldName Name of fieldName being generated ex. Model.created
  1833. * @param array $attributes Array of attributes, must contain 'empty' key.
  1834. * @return array Attributes array with currently selected value.
  1835. */
  1836. protected function _dateTimeSelected($select, $fieldName, $attributes) {
  1837. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  1838. if (is_array($value) && isset($value[$select])) {
  1839. $attributes['value'] = $value[$select];
  1840. } else {
  1841. if (empty($value)) {
  1842. if (!$attributes['empty']) {
  1843. $attributes['value'] = 'now';
  1844. }
  1845. } else {
  1846. $attributes['value'] = $value;
  1847. }
  1848. }
  1849. }
  1850. return $attributes;
  1851. }
  1852. /**
  1853. * Returns a SELECT element for AM or PM.
  1854. *
  1855. * ### Attributes:
  1856. *
  1857. * - `empty` - If true, the empty select option is shown. If a string,
  1858. * that string is displayed as the empty element.
  1859. * - `value` The selected value of the input.
  1860. *
  1861. * @param string $fieldName Prefix name for the SELECT element
  1862. * @param string $attributes Array of Attributes
  1863. * @return string Completed meridian select input
  1864. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::meridian
  1865. */
  1866. public function meridian($fieldName, $attributes = array()) {
  1867. $attributes += array('empty' => true, 'value' => null);
  1868. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  1869. if (is_array($value)) {
  1870. extract($value);
  1871. $attributes['value'] = $meridian;
  1872. } else {
  1873. if (empty($value)) {
  1874. if (!$attributes['empty']) {
  1875. $attributes['value'] = date('a');
  1876. }
  1877. } else {
  1878. $attributes['value'] = date('a', strtotime($value));
  1879. }
  1880. }
  1881. }
  1882. if ($attributes['value'] === false) {
  1883. $attributes['value'] = null;
  1884. }
  1885. return $this->select(
  1886. $fieldName . ".meridian", $this->_generateOptions('meridian'),
  1887. $attributes
  1888. );
  1889. }
  1890. /**
  1891. * Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
  1892. *
  1893. * ### Attributes:
  1894. *
  1895. * - `monthNames` If false, 2 digit numbers will be used instead of text.
  1896. * If a array, the given array will be used.
  1897. * - `minYear` The lowest year to use in the year select
  1898. * - `maxYear` The maximum year to use in the year select
  1899. * - `interval` The interval for the minutes select. Defaults to 1
  1900. * - `separator` The contents of the string between select elements. Defaults to '-'
  1901. * - `empty` - If true, the empty select option is shown. If a string,
  1902. * that string is displayed as the empty element.
  1903. * - `value` | `default` The default value to be used by the input. A value in `$this->data`
  1904. * matching the field name will override this value. If no default is provided `time()` will be used.
  1905. *
  1906. * @param string $fieldName Prefix name for the SELECT element
  1907. * @param string $dateFormat DMY, MDY, YMD.
  1908. * @param string $timeFormat 12, 24.
  1909. * @param string $attributes array of Attributes
  1910. * @return string Generated set of select boxes for the date and time formats chosen.
  1911. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::dateTime
  1912. */
  1913. public function dateTime($fieldName, $dateFormat = 'DMY', $timeFormat = '12', $attributes = array()) {
  1914. $attributes += array('empty' => true, 'value' => null);
  1915. $year = $month = $day = $hour = $min = $meridian = null;
  1916. if (empty($attributes['value'])) {
  1917. $attributes = $this->value($attributes, $fieldName);
  1918. }
  1919. if ($attributes['value'] === null && $attributes['empty'] != true) {
  1920. $attributes['value'] = time();
  1921. }
  1922. if (!empty($attributes['value'])) {
  1923. if (is_array($attributes['value'])) {
  1924. extract($attributes['value']);
  1925. } else {
  1926. if (is_numeric($attributes['value'])) {
  1927. $attributes['value'] = strftime('%Y-%m-%d %H:%M:%S', $attributes['value']);
  1928. }
  1929. $meridian = 'am';
  1930. $pos = strpos($attributes['value'], '-');
  1931. if ($pos !== false) {
  1932. $date = explode('-', $attributes['value']);
  1933. $days = explode(' ', $date[2]);
  1934. $day = $days[0];
  1935. $month = $date[1];
  1936. $year = $date[0];
  1937. } else {
  1938. $days[1] = $attributes['value'];
  1939. }
  1940. if (!empty($timeFormat)) {
  1941. $time = explode(':', $days[1]);
  1942. if (($time[0] > 12) && $timeFormat == '12') {
  1943. $time[0] = $time[0] - 12;
  1944. $meridian = 'pm';
  1945. } elseif ($time[0] == '12' && $timeFormat == '12') {
  1946. $meridian = 'pm';
  1947. } elseif ($time[0] == '00' && $timeFormat == '12') {
  1948. $time[0] = 12;
  1949. } elseif ($time[0] >= 12) {
  1950. $meridian = 'pm';
  1951. }
  1952. if ($time[0] == 0 && $timeFormat == '12') {
  1953. $time[0] = 12;
  1954. }
  1955. $hour = $min = null;
  1956. if (isset($time[1])) {
  1957. $hour = $time[0];
  1958. $min = $time[1];
  1959. }
  1960. }
  1961. }
  1962. }
  1963. $elements = array('Day', 'Month', 'Year', 'Hour', 'Minute', 'Meridian');
  1964. $defaults = array(
  1965. 'minYear' => null, 'maxYear' => null, 'separator' => '-',
  1966. 'interval' => 1, 'monthNames' => true
  1967. );
  1968. $attributes = array_merge($defaults, (array) $attributes);
  1969. if (isset($attributes['minuteInterval'])) {
  1970. $attributes['interval'] = $attributes['minuteInterval'];
  1971. unset($attributes['minuteInterval']);
  1972. }
  1973. $minYear = $attributes['minYear'];
  1974. $maxYear = $attributes['maxYear'];
  1975. $separator = $attributes['separator'];
  1976. $interval = $attributes['interval'];
  1977. $monthNames = $attributes['monthNames'];
  1978. $attributes = array_diff_key($attributes, $defaults);
  1979. if (isset($attributes['id'])) {
  1980. if (is_string($attributes['id'])) {
  1981. // build out an array version
  1982. foreach ($elements as $element) {
  1983. $selectAttrName = 'select' . $element . 'Attr';
  1984. ${$selectAttrName} = $attributes;
  1985. ${$selectAttrName}['id'] = $attributes['id'] . $element;
  1986. }
  1987. } elseif (is_array($attributes['id'])) {
  1988. // check for missing ones and build selectAttr for each element
  1989. $attributes['id'] += array(
  1990. 'month' => '', 'year' => '', 'day' => '',
  1991. 'hour' => '', 'minute' => '', 'meridian' => ''
  1992. );
  1993. foreach ($elements as $element) {
  1994. $selectAttrName = 'select' . $element . 'Attr';
  1995. ${$selectAttrName} = $attributes;
  1996. ${$selectAttrName}['id'] = $attributes['id'][strtolower($element)];
  1997. }
  1998. }
  1999. } else {
  2000. // build the selectAttrName with empty id's to pass
  2001. foreach ($elements as $element) {
  2002. $selectAttrName = 'select' . $element . 'Attr';
  2003. ${$selectAttrName} = $attributes;
  2004. }
  2005. }
  2006. $selects = array();
  2007. foreach (preg_split('//', $dateFormat, -1, PREG_SPLIT_NO_EMPTY) as $char) {
  2008. switch ($char) {
  2009. case 'Y':
  2010. $selectYearAttr['value'] = $year;
  2011. $selects[] = $this->year(
  2012. $fieldName, $minYear, $maxYear, $selectYearAttr
  2013. );
  2014. break;
  2015. case 'M':
  2016. $selectMonthAttr['value'] = $month;
  2017. $selectMonthAttr['monthNames'] = $monthNames;
  2018. $selects[] = $this->month($fieldName, $selectMonthAttr);
  2019. break;
  2020. case 'D':
  2021. $selectDayAttr['value'] = $day;
  2022. $selects[] = $this->day($fieldName, $selectDayAttr);
  2023. break;
  2024. }
  2025. }
  2026. $opt = implode($separator, $selects);
  2027. if (!empty($interval) && $interval > 1 && !empty($min)) {
  2028. $min = round($min * (1 / $interval)) * $interval;
  2029. }
  2030. $selectMinuteAttr['interval'] = $interval;
  2031. switch ($timeFormat) {
  2032. case '24':
  2033. $selectHourAttr['value'] = $hour;
  2034. $selectMinuteAttr['value'] = $min;
  2035. $opt .= $this->hour($fieldName, true, $selectHourAttr) . ':' .
  2036. $this->minute($fieldName, $selectMinuteAttr);
  2037. break;
  2038. case '12':
  2039. $selectHourAttr['value'] = $hour;
  2040. $selectMinuteAttr['value'] = $min;
  2041. $selectMeridianAttr['value'] = $meridian;
  2042. $opt .= $this->hour($fieldName, false, $selectHourAttr) . ':' .
  2043. $this->minute($fieldName, $selectMinuteAttr) . ' ' .
  2044. $this->meridian($fieldName, $selectMeridianAttr);
  2045. break;
  2046. default:
  2047. $opt .= '';
  2048. break;
  2049. }
  2050. return $opt;
  2051. }
  2052. /**
  2053. * Gets the input field name for the current tag
  2054. *
  2055. * @param array $options
  2056. * @param string $field
  2057. * @param string $key
  2058. * @return array
  2059. */
  2060. protected function _name($options = array(), $field = null, $key = 'name') {
  2061. if ($this->requestType == 'get') {
  2062. if ($options === null) {
  2063. $options = array();
  2064. } elseif (is_string($options)) {
  2065. $field = $options;
  2066. $options = 0;
  2067. }
  2068. if (!empty($field)) {
  2069. $this->setEntity($field);
  2070. }
  2071. if (is_array($options) && isset($options[$key])) {
  2072. return $options;
  2073. }
  2074. $entity = $this->entity();
  2075. $model = $this->model();
  2076. $name = $model === $entity[0] && isset($entity[1]) ? $entity[1] : $entity[0];
  2077. $last = $entity[count($entity) - 1];
  2078. if (in_array($last, $this->_fieldSuffixes)) {
  2079. $name .= '[' . $last . ']';
  2080. }
  2081. if (is_array($options)) {
  2082. $options[$key] = $name;
  2083. return $options;
  2084. } else {
  2085. return $name;
  2086. }
  2087. }
  2088. return parent::_name($options, $field, $key);
  2089. }
  2090. /**
  2091. * Returns an array of formatted OPTION/OPTGROUP elements
  2092. *
  2093. * @param array $elements
  2094. * @param array $parents
  2095. * @param boolean $showParents
  2096. * @param array $attributes
  2097. * @return array
  2098. */
  2099. protected function _selectOptions($elements = array(), $parents = array(), $showParents = null, $attributes = array()) {
  2100. $select = array();
  2101. $attributes = array_merge(
  2102. array('escape' => true, 'style' => null, 'value' => null, 'class' => null),
  2103. $attributes
  2104. );
  2105. $selectedIsEmpty = ($attributes['value'] === '' || $attributes['value'] === null);
  2106. $selectedIsArray = is_array($attributes['value']);
  2107. foreach ($elements as $name => $title) {
  2108. $htmlOptions = array();
  2109. if (is_array($title) && (!isset($title['name']) || !isset($title['value']))) {
  2110. if (!empty($name)) {
  2111. if ($attributes['style'] === 'checkbox') {
  2112. $select[] = $this->Html->useTag('fieldsetend');
  2113. } else {
  2114. $select[] = $this->Html->useTag('optiongroupend');
  2115. }
  2116. $parents[] = $name;
  2117. }
  2118. $select = array_merge($select, $this->_selectOptions(
  2119. $title, $parents, $showParents, $attributes
  2120. ));
  2121. if (!empty($name)) {
  2122. $name = $attributes['escape'] ? h($name) : $name;
  2123. if ($attributes['style'] === 'checkbox') {
  2124. $select[] = $this->Html->useTag('fieldsetstart', $name);
  2125. } else {
  2126. $select[] = $this->Html->useTag('optiongroup', $name, '');
  2127. }
  2128. }
  2129. $name = null;
  2130. } elseif (is_array($title)) {
  2131. $htmlOptions = $title;
  2132. $name = $title['value'];
  2133. $title = $title['name'];
  2134. unset($htmlOptions['name'], $htmlOptions['value']);
  2135. }
  2136. if ($name !== null) {
  2137. if (
  2138. (!$selectedIsArray && !$selectedIsEmpty && (string)$attributes['value'] == (string)$name) ||
  2139. ($selectedIsArray && in_array($name, $attributes['value']))
  2140. ) {
  2141. if ($attributes['style'] === 'checkbox') {
  2142. $htmlOptions['checked'] = true;
  2143. } else {
  2144. $htmlOptions['selected'] = 'selected';
  2145. }
  2146. }
  2147. if ($showParents || (!in_array($title, $parents))) {
  2148. $title = ($attributes['escape']) ? h($title) : $title;
  2149. if ($attributes['style'] === 'checkbox') {
  2150. $htmlOptions['value'] = $name;
  2151. $tagName = $attributes['id'] . Inflector::camelize(Inflector::slug($name));
  2152. $htmlOptions['id'] = $tagName;
  2153. $label = array('for' => $tagName);
  2154. if (isset($htmlOptions['checked']) && $htmlOptions['checked'] === true) {
  2155. $label['class'] = 'selected';
  2156. }
  2157. $name = $attributes['name'];
  2158. if (empty($attributes['class'])) {
  2159. $attributes['class'] = 'checkbox';
  2160. } elseif ($attributes['class'] === 'form-error') {
  2161. $attributes['class'] = 'checkbox ' . $attributes['class'];
  2162. }
  2163. $label = $this->label(null, $title, $label);
  2164. $item = $this->Html->useTag('checkboxmultiple', $name, $htmlOptions);
  2165. $select[] = $this->Html->div($attributes['class'], $item . $label);
  2166. } else {
  2167. $select[] = $this->Html->useTag('selectoption', $name, $htmlOptions, $title);
  2168. }
  2169. }
  2170. }
  2171. }
  2172. return array_reverse($select, true);
  2173. }
  2174. /**
  2175. * Generates option lists for common <select /> menus
  2176. *
  2177. * @param string $name
  2178. * @param array $options
  2179. * @return array
  2180. */
  2181. protected function _generateOptions($name, $options = array()) {
  2182. if (!empty($this->options[$name])) {
  2183. return $this->options[$name];
  2184. }
  2185. $data = array();
  2186. switch ($name) {
  2187. case 'minute':
  2188. if (isset($options['interval'])) {
  2189. $interval = $options['interval'];
  2190. } else {
  2191. $interval = 1;
  2192. }
  2193. $i = 0;
  2194. while ($i < 60) {
  2195. $data[sprintf('%02d', $i)] = sprintf('%02d', $i);
  2196. $i += $interval;
  2197. }
  2198. break;
  2199. case 'hour':
  2200. for ($i = 1; $i <= 12; $i++) {
  2201. $data[sprintf('%02d', $i)] = $i;
  2202. }
  2203. break;
  2204. case 'hour24':
  2205. for ($i = 0; $i <= 23; $i++) {
  2206. $data[sprintf('%02d', $i)] = $i;
  2207. }
  2208. break;
  2209. case 'meridian':
  2210. $data = array('am' => 'am', 'pm' => 'pm');
  2211. break;
  2212. case 'day':
  2213. $min = 1;
  2214. $max = 31;
  2215. if (isset($options['min'])) {
  2216. $min = $options['min'];
  2217. }
  2218. if (isset($options['max'])) {
  2219. $max = $options['max'];
  2220. }
  2221. for ($i = $min; $i <= $max; $i++) {
  2222. $data[sprintf('%02d', $i)] = $i;
  2223. }
  2224. break;
  2225. case 'month':
  2226. if ($options['monthNames'] === true) {
  2227. $data['01'] = __d('cake', 'January');
  2228. $data['02'] = __d('cake', 'February');
  2229. $data['03'] = __d('cake', 'March');
  2230. $data['04'] = __d('cake', 'April');
  2231. $data['05'] = __d('cake', 'May');
  2232. $data['06'] = __d('cake', 'June');
  2233. $data['07'] = __d('cake', 'July');
  2234. $data['08'] = __d('cake', 'August');
  2235. $data['09'] = __d('cake', 'September');
  2236. $data['10'] = __d('cake', 'October');
  2237. $data['11'] = __d('cake', 'November');
  2238. $data['12'] = __d('cake', 'December');
  2239. } else if (is_array($options['monthNames'])) {
  2240. $data = $options['monthNames'];
  2241. } else {
  2242. for ($m = 1; $m <= 12; $m++) {
  2243. $data[sprintf("%02s", $m)] = strftime("%m", mktime(1, 1, 1, $m, 1, 1999));
  2244. }
  2245. }
  2246. break;
  2247. case 'year':
  2248. $current = intval(date('Y'));
  2249. if (!isset($options['min'])) {
  2250. $min = $current - 20;
  2251. } else {
  2252. $min = $options['min'];
  2253. }
  2254. if (!isset($options['max'])) {
  2255. $max = $current + 20;
  2256. } else {
  2257. $max = $options['max'];
  2258. }
  2259. if ($min > $max) {
  2260. list($min, $max) = array($max, $min);
  2261. }
  2262. for ($i = $min; $i <= $max; $i++) {
  2263. $data[$i] = $i;
  2264. }
  2265. if ($options['order'] != 'asc') {
  2266. $data = array_reverse($data, true);
  2267. }
  2268. break;
  2269. }
  2270. $this->_options[$name] = $data;
  2271. return $this->_options[$name];
  2272. }
  2273. /**
  2274. * Sets field defaults and adds field to form security input hash
  2275. *
  2276. * ### Options
  2277. *
  2278. * - `secure` - boolean whether or not the field should be added to the security fields.
  2279. *
  2280. * @param string $field Name of the field to initialize options for.
  2281. * @param array $options Array of options to append options into.
  2282. * @return array Array of options for the input.
  2283. */
  2284. protected function _initInputField($field, $options = array()) {
  2285. if (isset($options['secure'])) {
  2286. $secure = $options['secure'];
  2287. unset($options['secure']);
  2288. } else {
  2289. $secure = (isset($this->request['_Token']) && !empty($this->request['_Token']));
  2290. }
  2291. $result = parent::_initInputField($field, $options);
  2292. if ($secure === self::SECURE_SKIP) {
  2293. return $result;
  2294. }
  2295. $fieldName = null;
  2296. if (!empty($options['name'])) {
  2297. preg_match_all('/\[(.*?)\]/', $options['name'], $matches);
  2298. if (isset($matches[1])) {
  2299. $fieldName = $matches[1];
  2300. }
  2301. }
  2302. $this->_secure($secure, $fieldName);
  2303. return $result;
  2304. }
  2305. }