FormHelper.php 91 KB

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