FormHelper.php 89 KB

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