FormHelper.php 89 KB

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