FormHelper.php 90 KB

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