FormHelper.php 88 KB

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