FormHelper.php 80 KB

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