FormHelper.php 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521
  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. $tag = $this->Html->useTag('submitimage', $url, $options);
  1495. } else {
  1496. $options['value'] = $caption;
  1497. $tag = $this->Html->useTag('submit', $options);
  1498. }
  1499. $out = $before . $tag . $after;
  1500. if (isset($divOptions)) {
  1501. $tag = $divOptions['tag'];
  1502. unset($divOptions['tag']);
  1503. $out = $this->Html->tag($tag, $out, $divOptions);
  1504. }
  1505. return $out;
  1506. }
  1507. /**
  1508. * Returns a formatted SELECT element.
  1509. *
  1510. * ### Attributes:
  1511. *
  1512. * - `showParents` - If included in the array and set to true, an additional option element
  1513. * will be added for the parent of each option group. You can set an option with the same name
  1514. * and it's key will be used for the value of the option.
  1515. * - `multiple` - show a multiple select box. If set to 'checkbox' multiple checkboxes will be
  1516. * created instead.
  1517. * - `empty` - If true, the empty select option is shown. If a string,
  1518. * that string is displayed as the empty element.
  1519. * - `escape` - If true contents of options will be HTML entity encoded. Defaults to true.
  1520. * - `value` The selected value of the input.
  1521. * - `class` - When using multiple = checkbox the classname to apply to the divs. Defaults to 'checkbox'.
  1522. *
  1523. * ### Using options
  1524. *
  1525. * A simple array will create normal options:
  1526. *
  1527. * {{{
  1528. * $options = array(1 => 'one', 2 => 'two);
  1529. * $this->Form->select('Model.field', $options));
  1530. * }}}
  1531. *
  1532. * While a nested options array will create optgroups with options inside them.
  1533. * {{{
  1534. * $options = array(
  1535. * 1 => 'bill',
  1536. * 'fred' => array(
  1537. * 2 => 'fred',
  1538. * 3 => 'fred jr.'
  1539. * )
  1540. * );
  1541. * $this->Form->select('Model.field', $options);
  1542. * }}}
  1543. *
  1544. * In the above `2 => 'fred'` will not generate an option element. You should enable the `showParents`
  1545. * attribute to show the fred option.
  1546. *
  1547. * @param string $fieldName Name attribute of the SELECT
  1548. * @param array $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the
  1549. * SELECT element
  1550. * @param array $attributes The HTML attributes of the select element.
  1551. * @return string Formatted SELECT element
  1552. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
  1553. */
  1554. public function select($fieldName, $options = array(), $attributes = array()) {
  1555. $select = array();
  1556. $style = null;
  1557. $tag = null;
  1558. $attributes += array(
  1559. 'class' => null,
  1560. 'escape' => true,
  1561. 'secure' => true,
  1562. 'empty' => '',
  1563. 'showParents' => false,
  1564. 'hiddenField' => true
  1565. );
  1566. $escapeOptions = $this->_extractOption('escape', $attributes);
  1567. $secure = $this->_extractOption('secure', $attributes);
  1568. $showEmpty = $this->_extractOption('empty', $attributes);
  1569. $showParents = $this->_extractOption('showParents', $attributes);
  1570. $hiddenField = $this->_extractOption('hiddenField', $attributes);
  1571. unset($attributes['escape'], $attributes['secure'], $attributes['empty'], $attributes['showParents'], $attributes['hiddenField']);
  1572. $id = $this->_extractOption('id', $attributes);
  1573. $attributes = $this->_initInputField($fieldName, array_merge(
  1574. (array)$attributes, array('secure' => self::SECURE_SKIP)
  1575. ));
  1576. if (is_string($options) && isset($this->_options[$options])) {
  1577. $options = $this->_generateOptions($options);
  1578. } elseif (!is_array($options)) {
  1579. $options = array();
  1580. }
  1581. if (isset($attributes['type'])) {
  1582. unset($attributes['type']);
  1583. }
  1584. if (!isset($selected)) {
  1585. $selected = $attributes['value'];
  1586. }
  1587. if (!empty($attributes['multiple'])) {
  1588. $style = ($attributes['multiple'] === 'checkbox') ? 'checkbox' : null;
  1589. $template = ($style) ? 'checkboxmultiplestart' : 'selectmultiplestart';
  1590. $tag = $template;
  1591. if ($hiddenField) {
  1592. $hiddenAttributes = array(
  1593. 'value' => '',
  1594. 'id' => $attributes['id'] . ($style ? '' : '_'),
  1595. 'secure' => false,
  1596. 'name' => $attributes['name']
  1597. );
  1598. $select[] = $this->hidden(null, $hiddenAttributes);
  1599. }
  1600. } else {
  1601. $tag = 'selectstart';
  1602. }
  1603. if (!empty($tag) || isset($template)) {
  1604. if (!isset($secure) || $secure == true) {
  1605. $this->_secure(true);
  1606. }
  1607. $select[] = $this->Html->useTag($tag, $attributes['name'], array_diff_key($attributes, array('name' => '', 'value' => '')));
  1608. }
  1609. $emptyMulti = (
  1610. $showEmpty !== null && $showEmpty !== false && !(
  1611. empty($showEmpty) && (isset($attributes) &&
  1612. array_key_exists('multiple', $attributes))
  1613. )
  1614. );
  1615. if ($emptyMulti) {
  1616. $showEmpty = ($showEmpty === true) ? '' : $showEmpty;
  1617. $options = array_reverse($options, true);
  1618. $options[''] = $showEmpty;
  1619. $options = array_reverse($options, true);
  1620. }
  1621. if (!$id) {
  1622. $attributes['id'] = Inflector::camelize($attributes['id']);
  1623. }
  1624. $select = array_merge($select, $this->_selectOptions(
  1625. array_reverse($options, true),
  1626. array(),
  1627. $showParents,
  1628. array(
  1629. 'escape' => $escapeOptions,
  1630. 'style' => $style,
  1631. 'name' => $attributes['name'],
  1632. 'value' => $attributes['value'],
  1633. 'class' => $attributes['class'],
  1634. 'id' => $attributes['id']
  1635. )
  1636. ));
  1637. $template = ($style == 'checkbox') ? 'checkboxmultipleend' : 'selectend';
  1638. $select[] = $this->Html->useTag($template);
  1639. return implode("\n", $select);
  1640. }
  1641. /**
  1642. * Returns a SELECT element for days.
  1643. *
  1644. * ### Attributes:
  1645. *
  1646. * - `empty` - If true, the empty select option is shown. If a string,
  1647. * that string is displayed as the empty element.
  1648. * - `value` The selected value of the input.
  1649. *
  1650. * @param string $fieldName Prefix name for the SELECT element
  1651. * @param array $attributes HTML attributes for the select element
  1652. * @return string A generated day select box.
  1653. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::day
  1654. */
  1655. public function day($fieldName = null, $attributes = array()) {
  1656. $attributes += array('empty' => true, 'value' => null);
  1657. $attributes = $this->_dateTimeSelected('day', $fieldName, $attributes);
  1658. if (strlen($attributes['value']) > 2) {
  1659. $attributes['value'] = date('d', strtotime($attributes['value']));
  1660. } elseif ($attributes['value'] === false) {
  1661. $attributes['value'] = null;
  1662. }
  1663. return $this->select($fieldName . ".day", $this->_generateOptions('day'), $attributes);
  1664. }
  1665. /**
  1666. * Returns a SELECT element for years
  1667. *
  1668. * ### Attributes:
  1669. *
  1670. * - `empty` - If true, the empty select option is shown. If a string,
  1671. * that string is displayed as the empty element.
  1672. * - `orderYear` - Ordering of year values in select options.
  1673. * Possible values 'asc', 'desc'. Default 'desc'
  1674. * - `value` The selected value of the input.
  1675. *
  1676. * @param string $fieldName Prefix name for the SELECT element
  1677. * @param integer $minYear First year in sequence
  1678. * @param integer $maxYear Last year in sequence
  1679. * @param array $attributes Attribute array for the select elements.
  1680. * @return string Completed year select input
  1681. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::year
  1682. */
  1683. public function year($fieldName, $minYear = null, $maxYear = null, $attributes = array()) {
  1684. $attributes += array('empty' => true, 'value' => null);
  1685. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  1686. if (is_array($value)) {
  1687. extract($value);
  1688. $attributes['value'] = $year;
  1689. } else {
  1690. if (empty($value)) {
  1691. if (!$attributes['empty'] && !$maxYear) {
  1692. $attributes['value'] = 'now';
  1693. } elseif (!$attributes['empty'] && $maxYear && !$attributes['value']) {
  1694. $attributes['value'] = $maxYear;
  1695. }
  1696. } else {
  1697. $attributes['value'] = $value;
  1698. }
  1699. }
  1700. }
  1701. if (strlen($attributes['value']) > 4 || $attributes['value'] === 'now') {
  1702. $attributes['value'] = date('Y', strtotime($attributes['value']));
  1703. } elseif ($attributes['value'] === false) {
  1704. $attributes['value'] = null;
  1705. }
  1706. $yearOptions = array('min' => $minYear, 'max' => $maxYear, 'order' => 'desc');
  1707. if (isset($attributes['orderYear'])) {
  1708. $yearOptions['order'] = $attributes['orderYear'];
  1709. unset($attributes['orderYear']);
  1710. }
  1711. return $this->select(
  1712. $fieldName . '.year', $this->_generateOptions('year', $yearOptions),
  1713. $attributes
  1714. );
  1715. }
  1716. /**
  1717. * Returns a SELECT element for months.
  1718. *
  1719. * ### Attributes:
  1720. *
  1721. * - `monthNames` - If false, 2 digit numbers will be used instead of text.
  1722. * If a array, the given array will be used.
  1723. * - `empty` - If true, the empty select option is shown. If a string,
  1724. * that string is displayed as the empty element.
  1725. * - `value` The selected value of the input.
  1726. *
  1727. * @param string $fieldName Prefix name for the SELECT element
  1728. * @param array $attributes Attributes for the select element
  1729. * @return string A generated month select dropdown.
  1730. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::month
  1731. */
  1732. public function month($fieldName, $attributes = array()) {
  1733. $attributes += array('empty' => true, 'value' => null);
  1734. $attributes = $this->_dateTimeSelected('month', $fieldName, $attributes);
  1735. if (strlen($attributes['value']) > 2) {
  1736. $attributes['value'] = date('m', strtotime($attributes['value']));
  1737. } elseif ($attributes['value'] === false) {
  1738. $attributes['value'] = null;
  1739. }
  1740. $defaults = array('monthNames' => true);
  1741. $attributes = array_merge($defaults, (array) $attributes);
  1742. $monthNames = $attributes['monthNames'];
  1743. unset($attributes['monthNames']);
  1744. return $this->select(
  1745. $fieldName . ".month",
  1746. $this->_generateOptions('month', array('monthNames' => $monthNames)),
  1747. $attributes
  1748. );
  1749. }
  1750. /**
  1751. * Returns a SELECT element for hours.
  1752. *
  1753. * ### Attributes:
  1754. *
  1755. * - `empty` - If true, the empty select option is shown. If a string,
  1756. * that string is displayed as the empty element.
  1757. * - `value` The selected value of the input.
  1758. *
  1759. * @param string $fieldName Prefix name for the SELECT element
  1760. * @param boolean $format24Hours True for 24 hours format
  1761. * @param array $attributes List of HTML attributes
  1762. * @return string Completed hour select input
  1763. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hour
  1764. */
  1765. public function hour($fieldName, $format24Hours = false, $attributes = array()) {
  1766. $attributes += array('empty' => true, 'value' => null);
  1767. $attributes = $this->_dateTimeSelected('hour', $fieldName, $attributes);
  1768. if (strlen($attributes['value']) > 2) {
  1769. if ($format24Hours) {
  1770. $attributes['value'] = date('H', strtotime($attributes['value']));
  1771. } else {
  1772. $attributes['value'] = date('g', strtotime($attributes['value']));
  1773. }
  1774. } elseif ($attributes['value'] === false) {
  1775. $attributes['value'] = null;
  1776. }
  1777. return $this->select(
  1778. $fieldName . ".hour",
  1779. $this->_generateOptions($format24Hours ? 'hour24' : 'hour'),
  1780. $attributes
  1781. );
  1782. }
  1783. /**
  1784. * Returns a SELECT element for minutes.
  1785. *
  1786. * ### Attributes:
  1787. *
  1788. * - `empty` - If true, the empty select option is shown. If a string,
  1789. * that string is displayed as the empty element.
  1790. * - `value` The selected value of the input.
  1791. *
  1792. * @param string $fieldName Prefix name for the SELECT element
  1793. * @param string $attributes Array of Attributes
  1794. * @return string Completed minute select input.
  1795. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::minute
  1796. */
  1797. public function minute($fieldName, $attributes = array()) {
  1798. $attributes += array('empty' => true, 'value' => null);
  1799. $attributes = $this->_dateTimeSelected('min', $fieldName, $attributes);
  1800. if (strlen($attributes['value']) > 2) {
  1801. $attributes['value'] = date('i', strtotime($attributes['value']));
  1802. } elseif ($attributes['value'] === false) {
  1803. $attributes['value'] = null;
  1804. }
  1805. $minuteOptions = array();
  1806. if (isset($attributes['interval'])) {
  1807. $minuteOptions['interval'] = $attributes['interval'];
  1808. unset($attributes['interval']);
  1809. }
  1810. return $this->select(
  1811. $fieldName . ".min", $this->_generateOptions('minute', $minuteOptions),
  1812. $attributes
  1813. );
  1814. }
  1815. /**
  1816. * Selects values for dateTime selects.
  1817. *
  1818. * @param string $select Name of element field. ex. 'day'
  1819. * @param string $fieldName Name of fieldName being generated ex. Model.created
  1820. * @param array $attributes Array of attributes, must contain 'empty' key.
  1821. * @return array Attributes array with currently selected value.
  1822. */
  1823. protected function _dateTimeSelected($select, $fieldName, $attributes) {
  1824. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  1825. if (is_array($value) && isset($value[$select])) {
  1826. $attributes['value'] = $value[$select];
  1827. } else {
  1828. if (empty($value)) {
  1829. if (!$attributes['empty']) {
  1830. $attributes['value'] = 'now';
  1831. }
  1832. } else {
  1833. $attributes['value'] = $value;
  1834. }
  1835. }
  1836. }
  1837. return $attributes;
  1838. }
  1839. /**
  1840. * Returns a SELECT element for AM or PM.
  1841. *
  1842. * ### Attributes:
  1843. *
  1844. * - `empty` - If true, the empty select option is shown. If a string,
  1845. * that string is displayed as the empty element.
  1846. * - `value` The selected value of the input.
  1847. *
  1848. * @param string $fieldName Prefix name for the SELECT element
  1849. * @param string $attributes Array of Attributes
  1850. * @return string Completed meridian select input
  1851. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::meridian
  1852. */
  1853. public function meridian($fieldName, $attributes = array()) {
  1854. $attributes += array('empty' => true, 'value' => null);
  1855. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  1856. if (is_array($value)) {
  1857. extract($value);
  1858. $attributes['value'] = $meridian;
  1859. } else {
  1860. if (empty($value)) {
  1861. if (!$attributes['empty']) {
  1862. $attributes['value'] = date('a');
  1863. }
  1864. } else {
  1865. $attributes['value'] = date('a', strtotime($value));
  1866. }
  1867. }
  1868. }
  1869. if ($attributes['value'] === false) {
  1870. $attributes['value'] = null;
  1871. }
  1872. return $this->select(
  1873. $fieldName . ".meridian", $this->_generateOptions('meridian'),
  1874. $attributes
  1875. );
  1876. }
  1877. /**
  1878. * Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
  1879. *
  1880. * ### Attributes:
  1881. *
  1882. * - `monthNames` If false, 2 digit numbers will be used instead of text.
  1883. * If a array, the given array will be used.
  1884. * - `minYear` The lowest year to use in the year select
  1885. * - `maxYear` The maximum year to use in the year select
  1886. * - `interval` The interval for the minutes select. Defaults to 1
  1887. * - `separator` The contents of the string between select elements. Defaults to '-'
  1888. * - `empty` - If true, the empty select option is shown. If a string,
  1889. * that string is displayed as the empty element.
  1890. * - `value` | `default` The default value to be used by the input. A value in `$this->data`
  1891. * matching the field name will override this value. If no default is provided `time()` will be used.
  1892. *
  1893. * @param string $fieldName Prefix name for the SELECT element
  1894. * @param string $dateFormat DMY, MDY, YMD.
  1895. * @param string $timeFormat 12, 24.
  1896. * @param string $attributes array of Attributes
  1897. * @return string Generated set of select boxes for the date and time formats chosen.
  1898. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::dateTime
  1899. */
  1900. public function dateTime($fieldName, $dateFormat = 'DMY', $timeFormat = '12', $attributes = array()) {
  1901. $attributes += array('empty' => true, 'value' => null);
  1902. $year = $month = $day = $hour = $min = $meridian = null;
  1903. if (empty($attributes['value'])) {
  1904. $attributes = $this->value($attributes, $fieldName);
  1905. }
  1906. if ($attributes['value'] === null && $attributes['empty'] != true) {
  1907. $attributes['value'] = time();
  1908. }
  1909. if (!empty($attributes['value'])) {
  1910. if (is_array($attributes['value'])) {
  1911. extract($attributes['value']);
  1912. } else {
  1913. if (is_numeric($attributes['value'])) {
  1914. $attributes['value'] = strftime('%Y-%m-%d %H:%M:%S', $attributes['value']);
  1915. }
  1916. $meridian = 'am';
  1917. $pos = strpos($attributes['value'], '-');
  1918. if ($pos !== false) {
  1919. $date = explode('-', $attributes['value']);
  1920. $days = explode(' ', $date[2]);
  1921. $day = $days[0];
  1922. $month = $date[1];
  1923. $year = $date[0];
  1924. } else {
  1925. $days[1] = $attributes['value'];
  1926. }
  1927. if (!empty($timeFormat)) {
  1928. $time = explode(':', $days[1]);
  1929. if (($time[0] > 12) && $timeFormat == '12') {
  1930. $time[0] = $time[0] - 12;
  1931. $meridian = 'pm';
  1932. } elseif ($time[0] == '12' && $timeFormat == '12') {
  1933. $meridian = 'pm';
  1934. } elseif ($time[0] == '00' && $timeFormat == '12') {
  1935. $time[0] = 12;
  1936. } elseif ($time[0] >= 12) {
  1937. $meridian = 'pm';
  1938. }
  1939. if ($time[0] == 0 && $timeFormat == '12') {
  1940. $time[0] = 12;
  1941. }
  1942. $hour = $min = null;
  1943. if (isset($time[1])) {
  1944. $hour = $time[0];
  1945. $min = $time[1];
  1946. }
  1947. }
  1948. }
  1949. }
  1950. $elements = array('Day', 'Month', 'Year', 'Hour', 'Minute', 'Meridian');
  1951. $defaults = array(
  1952. 'minYear' => null, 'maxYear' => null, 'separator' => '-',
  1953. 'interval' => 1, 'monthNames' => true
  1954. );
  1955. $attributes = array_merge($defaults, (array) $attributes);
  1956. if (isset($attributes['minuteInterval'])) {
  1957. $attributes['interval'] = $attributes['minuteInterval'];
  1958. unset($attributes['minuteInterval']);
  1959. }
  1960. $minYear = $attributes['minYear'];
  1961. $maxYear = $attributes['maxYear'];
  1962. $separator = $attributes['separator'];
  1963. $interval = $attributes['interval'];
  1964. $monthNames = $attributes['monthNames'];
  1965. $attributes = array_diff_key($attributes, $defaults);
  1966. if (isset($attributes['id'])) {
  1967. if (is_string($attributes['id'])) {
  1968. // build out an array version
  1969. foreach ($elements as $element) {
  1970. $selectAttrName = 'select' . $element . 'Attr';
  1971. ${$selectAttrName} = $attributes;
  1972. ${$selectAttrName}['id'] = $attributes['id'] . $element;
  1973. }
  1974. } elseif (is_array($attributes['id'])) {
  1975. // check for missing ones and build selectAttr for each element
  1976. $attributes['id'] += array(
  1977. 'month' => '', 'year' => '', 'day' => '',
  1978. 'hour' => '', 'minute' => '', 'meridian' => ''
  1979. );
  1980. foreach ($elements as $element) {
  1981. $selectAttrName = 'select' . $element . 'Attr';
  1982. ${$selectAttrName} = $attributes;
  1983. ${$selectAttrName}['id'] = $attributes['id'][strtolower($element)];
  1984. }
  1985. }
  1986. } else {
  1987. // build the selectAttrName with empty id's to pass
  1988. foreach ($elements as $element) {
  1989. $selectAttrName = 'select' . $element . 'Attr';
  1990. ${$selectAttrName} = $attributes;
  1991. }
  1992. }
  1993. $selects = array();
  1994. foreach (preg_split('//', $dateFormat, -1, PREG_SPLIT_NO_EMPTY) as $char) {
  1995. switch ($char) {
  1996. case 'Y':
  1997. $selectYearAttr['value'] = $year;
  1998. $selects[] = $this->year(
  1999. $fieldName, $minYear, $maxYear, $selectYearAttr
  2000. );
  2001. break;
  2002. case 'M':
  2003. $selectMonthAttr['value'] = $month;
  2004. $selectMonthAttr['monthNames'] = $monthNames;
  2005. $selects[] = $this->month($fieldName, $selectMonthAttr);
  2006. break;
  2007. case 'D':
  2008. $selectDayAttr['value'] = $day;
  2009. $selects[] = $this->day($fieldName, $selectDayAttr);
  2010. break;
  2011. }
  2012. }
  2013. $opt = implode($separator, $selects);
  2014. if (!empty($interval) && $interval > 1 && !empty($min)) {
  2015. $min = round($min * (1 / $interval)) * $interval;
  2016. }
  2017. $selectMinuteAttr['interval'] = $interval;
  2018. switch ($timeFormat) {
  2019. case '24':
  2020. $selectHourAttr['value'] = $hour;
  2021. $selectMinuteAttr['value'] = $min;
  2022. $opt .= $this->hour($fieldName, true, $selectHourAttr) . ':' .
  2023. $this->minute($fieldName, $selectMinuteAttr);
  2024. break;
  2025. case '12':
  2026. $selectHourAttr['value'] = $hour;
  2027. $selectMinuteAttr['value'] = $min;
  2028. $selectMeridianAttr['value'] = $meridian;
  2029. $opt .= $this->hour($fieldName, false, $selectHourAttr) . ':' .
  2030. $this->minute($fieldName, $selectMinuteAttr) . ' ' .
  2031. $this->meridian($fieldName, $selectMeridianAttr);
  2032. break;
  2033. default:
  2034. $opt .= '';
  2035. break;
  2036. }
  2037. return $opt;
  2038. }
  2039. /**
  2040. * Add support for special HABTM syntax.
  2041. *
  2042. * Sets this helper's model and field properties to the dot-separated value-pair in $entity.
  2043. *
  2044. * @param mixed $entity A field name, like "ModelName.fieldName" or "ModelName.ID.fieldName"
  2045. * @param boolean $setScope Sets the view scope to the model specified in $tagValue
  2046. * @return void
  2047. */
  2048. public function setEntity($entity, $setScope = false) {
  2049. parent::setEntity($entity, $setScope);
  2050. $parts = explode('.', $entity);
  2051. $field = $this->_introspectModel($this->_modelScope, 'fields', $parts[0]);
  2052. if (!empty($field) && $field['type'] === 'multiple') {
  2053. $this->_entityPath = $parts[0] . '.' . $parts[0];
  2054. }
  2055. }
  2056. /**
  2057. * Gets the input field name for the current tag
  2058. *
  2059. * @param array $options
  2060. * @param string $field
  2061. * @param string $key
  2062. * @return array
  2063. */
  2064. protected function _name($options = array(), $field = null, $key = 'name') {
  2065. if ($this->requestType == 'get') {
  2066. if ($options === null) {
  2067. $options = array();
  2068. } elseif (is_string($options)) {
  2069. $field = $options;
  2070. $options = 0;
  2071. }
  2072. if (!empty($field)) {
  2073. $this->setEntity($field);
  2074. }
  2075. if (is_array($options) && isset($options[$key])) {
  2076. return $options;
  2077. }
  2078. $entity = $this->entity();
  2079. $model = $this->model();
  2080. $name = $model === $entity[0] && isset($entity[1]) ? $entity[1] : $entity[0];
  2081. $last = $entity[count($entity) - 1];
  2082. if (in_array($last, $this->_fieldSuffixes)) {
  2083. $name .= '[' . $last . ']';
  2084. }
  2085. if (is_array($options)) {
  2086. $options[$key] = $name;
  2087. return $options;
  2088. } else {
  2089. return $name;
  2090. }
  2091. }
  2092. return parent::_name($options, $field, $key);
  2093. }
  2094. /**
  2095. * Returns an array of formatted OPTION/OPTGROUP elements
  2096. *
  2097. * @param array $elements
  2098. * @param array $parents
  2099. * @param boolean $showParents
  2100. * @param array $attributes
  2101. * @return array
  2102. */
  2103. protected function _selectOptions($elements = array(), $parents = array(), $showParents = null, $attributes = array()) {
  2104. $select = array();
  2105. $attributes = array_merge(
  2106. array('escape' => true, 'style' => null, 'value' => null, 'class' => null),
  2107. $attributes
  2108. );
  2109. $selectedIsEmpty = ($attributes['value'] === '' || $attributes['value'] === null);
  2110. $selectedIsArray = is_array($attributes['value']);
  2111. foreach ($elements as $name => $title) {
  2112. $htmlOptions = array();
  2113. if (is_array($title) && (!isset($title['name']) || !isset($title['value']))) {
  2114. if (!empty($name)) {
  2115. if ($attributes['style'] === 'checkbox') {
  2116. $select[] = $this->Html->useTag('fieldsetend');
  2117. } else {
  2118. $select[] = $this->Html->useTag('optiongroupend');
  2119. }
  2120. $parents[] = $name;
  2121. }
  2122. $select = array_merge($select, $this->_selectOptions(
  2123. $title, $parents, $showParents, $attributes
  2124. ));
  2125. if (!empty($name)) {
  2126. $name = $attributes['escape'] ? h($name) : $name;
  2127. if ($attributes['style'] === 'checkbox') {
  2128. $select[] = $this->Html->useTag('fieldsetstart', $name);
  2129. } else {
  2130. $select[] = $this->Html->useTag('optiongroup', $name, '');
  2131. }
  2132. }
  2133. $name = null;
  2134. } elseif (is_array($title)) {
  2135. $htmlOptions = $title;
  2136. $name = $title['value'];
  2137. $title = $title['name'];
  2138. unset($htmlOptions['name'], $htmlOptions['value']);
  2139. }
  2140. if ($name !== null) {
  2141. if (
  2142. (!$selectedIsArray && !$selectedIsEmpty && (string)$attributes['value'] == (string)$name) ||
  2143. ($selectedIsArray && in_array($name, $attributes['value']))
  2144. ) {
  2145. if ($attributes['style'] === 'checkbox') {
  2146. $htmlOptions['checked'] = true;
  2147. } else {
  2148. $htmlOptions['selected'] = 'selected';
  2149. }
  2150. }
  2151. if ($showParents || (!in_array($title, $parents))) {
  2152. $title = ($attributes['escape']) ? h($title) : $title;
  2153. if ($attributes['style'] === 'checkbox') {
  2154. $htmlOptions['value'] = $name;
  2155. $tagName = $attributes['id'] . Inflector::camelize(Inflector::slug($name));
  2156. $htmlOptions['id'] = $tagName;
  2157. $label = array('for' => $tagName);
  2158. if (isset($htmlOptions['checked']) && $htmlOptions['checked'] === true) {
  2159. $label['class'] = 'selected';
  2160. }
  2161. $name = $attributes['name'];
  2162. if (empty($attributes['class'])) {
  2163. $attributes['class'] = 'checkbox';
  2164. } elseif ($attributes['class'] === 'form-error') {
  2165. $attributes['class'] = 'checkbox ' . $attributes['class'];
  2166. }
  2167. $label = $this->label(null, $title, $label);
  2168. $item = $this->Html->useTag('checkboxmultiple', $name, $htmlOptions);
  2169. $select[] = $this->Html->div($attributes['class'], $item . $label);
  2170. } else {
  2171. $select[] = $this->Html->useTag('selectoption', $name, $htmlOptions, $title);
  2172. }
  2173. }
  2174. }
  2175. }
  2176. return array_reverse($select, true);
  2177. }
  2178. /**
  2179. * Generates option lists for common <select /> menus
  2180. *
  2181. * @param string $name
  2182. * @param array $options
  2183. * @return array
  2184. */
  2185. protected function _generateOptions($name, $options = array()) {
  2186. if (!empty($this->options[$name])) {
  2187. return $this->options[$name];
  2188. }
  2189. $data = array();
  2190. switch ($name) {
  2191. case 'minute':
  2192. if (isset($options['interval'])) {
  2193. $interval = $options['interval'];
  2194. } else {
  2195. $interval = 1;
  2196. }
  2197. $i = 0;
  2198. while ($i < 60) {
  2199. $data[sprintf('%02d', $i)] = sprintf('%02d', $i);
  2200. $i += $interval;
  2201. }
  2202. break;
  2203. case 'hour':
  2204. for ($i = 1; $i <= 12; $i++) {
  2205. $data[sprintf('%02d', $i)] = $i;
  2206. }
  2207. break;
  2208. case 'hour24':
  2209. for ($i = 0; $i <= 23; $i++) {
  2210. $data[sprintf('%02d', $i)] = $i;
  2211. }
  2212. break;
  2213. case 'meridian':
  2214. $data = array('am' => 'am', 'pm' => 'pm');
  2215. break;
  2216. case 'day':
  2217. $min = 1;
  2218. $max = 31;
  2219. if (isset($options['min'])) {
  2220. $min = $options['min'];
  2221. }
  2222. if (isset($options['max'])) {
  2223. $max = $options['max'];
  2224. }
  2225. for ($i = $min; $i <= $max; $i++) {
  2226. $data[sprintf('%02d', $i)] = $i;
  2227. }
  2228. break;
  2229. case 'month':
  2230. if ($options['monthNames'] === true) {
  2231. $data['01'] = __('January');
  2232. $data['02'] = __('February');
  2233. $data['03'] = __('March');
  2234. $data['04'] = __('April');
  2235. $data['05'] = __('May');
  2236. $data['06'] = __('June');
  2237. $data['07'] = __('July');
  2238. $data['08'] = __('August');
  2239. $data['09'] = __('September');
  2240. $data['10'] = __('October');
  2241. $data['11'] = __('November');
  2242. $data['12'] = __('December');
  2243. } else if (is_array($options['monthNames'])) {
  2244. $data = $options['monthNames'];
  2245. } else {
  2246. for ($m = 1; $m <= 12; $m++) {
  2247. $data[sprintf("%02s", $m)] = strftime("%m", mktime(1, 1, 1, $m, 1, 1999));
  2248. }
  2249. }
  2250. break;
  2251. case 'year':
  2252. $current = intval(date('Y'));
  2253. if (!isset($options['min'])) {
  2254. $min = $current - 20;
  2255. } else {
  2256. $min = $options['min'];
  2257. }
  2258. if (!isset($options['max'])) {
  2259. $max = $current + 20;
  2260. } else {
  2261. $max = $options['max'];
  2262. }
  2263. if ($min > $max) {
  2264. list($min, $max) = array($max, $min);
  2265. }
  2266. for ($i = $min; $i <= $max; $i++) {
  2267. $data[$i] = $i;
  2268. }
  2269. if ($options['order'] != 'asc') {
  2270. $data = array_reverse($data, true);
  2271. }
  2272. break;
  2273. }
  2274. $this->_options[$name] = $data;
  2275. return $this->_options[$name];
  2276. }
  2277. /**
  2278. * Sets field defaults and adds field to form security input hash
  2279. *
  2280. * ### Options
  2281. *
  2282. * - `secure` - boolean whether or not the field should be added to the security fields.
  2283. *
  2284. * @param string $field Name of the field to initialize options for.
  2285. * @param array $options Array of options to append options into.
  2286. * @return array Array of options for the input.
  2287. */
  2288. protected function _initInputField($field, $options = array()) {
  2289. if (isset($options['secure'])) {
  2290. $secure = $options['secure'];
  2291. unset($options['secure']);
  2292. } else {
  2293. $secure = (isset($this->request['_Token']) && !empty($this->request['_Token']));
  2294. }
  2295. $result = parent::_initInputField($field, $options);
  2296. if ($secure === self::SECURE_SKIP) {
  2297. return $result;
  2298. }
  2299. $fieldName = null;
  2300. if (!empty($options['name'])) {
  2301. preg_match_all('/\[(.*?)\]/', $options['name'], $matches);
  2302. if (isset($matches[1])) {
  2303. $fieldName = $matches[1];
  2304. }
  2305. }
  2306. $this->_secure($secure, $fieldName);
  2307. return $result;
  2308. }
  2309. }