FormHelper.php 92 KB

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