FormHelper.php 93 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', 'decimal' => 'number',
  1058. 'binary' => 'file'
  1059. );
  1060. if (isset($this->map[$type])) {
  1061. $options['type'] = $this->map[$type];
  1062. } elseif (isset($map[$type])) {
  1063. $options['type'] = $map[$type];
  1064. }
  1065. if ($fieldKey == $primaryKey) {
  1066. $options['type'] = 'hidden';
  1067. }
  1068. if (
  1069. $options['type'] === 'number' &&
  1070. !isset($options['step'])
  1071. ) {
  1072. if ($type === 'decimal') {
  1073. $options['step'] = pow(10, -1 * substr($fieldDef['length'], strpos($fieldDef['length'], ',') + 1));
  1074. } elseif ($type === 'float') {
  1075. $options['step'] = 'any';
  1076. }
  1077. }
  1078. }
  1079. if (preg_match('/_id$/', $fieldKey) && $options['type'] !== 'hidden') {
  1080. $options['type'] = 'select';
  1081. }
  1082. if ($modelKey === $fieldKey) {
  1083. $options['type'] = 'select';
  1084. if (!isset($options['multiple'])) {
  1085. $options['multiple'] = 'multiple';
  1086. }
  1087. }
  1088. if (in_array($options['type'], array('text', 'number'))) {
  1089. $options = $this->_optionsOptions($options);
  1090. }
  1091. if ($options['type'] === 'select' && array_key_exists('step', $options)) {
  1092. unset($options['step']);
  1093. }
  1094. $options = $this->_maxLength($options);
  1095. return $options;
  1096. }
  1097. /**
  1098. * Generate format options
  1099. *
  1100. * @param array $options
  1101. * @return array
  1102. */
  1103. protected function _getFormat($options) {
  1104. if ($options['type'] === 'hidden') {
  1105. return array('input');
  1106. }
  1107. if (is_array($options['format']) && in_array('input', $options['format'])) {
  1108. return $options['format'];
  1109. }
  1110. if ($options['type'] === 'checkbox') {
  1111. return array('before', 'input', 'between', 'label', 'after', 'error');
  1112. }
  1113. return array('before', 'label', 'between', 'input', 'after', 'error');
  1114. }
  1115. /**
  1116. * Generate label for input
  1117. *
  1118. * @param string $fieldName
  1119. * @param array $options
  1120. * @return boolean|string false or Generated label element
  1121. */
  1122. protected function _getLabel($fieldName, $options) {
  1123. if ($options['type'] === 'radio') {
  1124. return false;
  1125. }
  1126. $label = null;
  1127. if (isset($options['label'])) {
  1128. $label = $options['label'];
  1129. }
  1130. if ($label === false) {
  1131. return false;
  1132. }
  1133. return $this->_inputLabel($fieldName, $label, $options);
  1134. }
  1135. /**
  1136. * Calculates maxlength option
  1137. *
  1138. * @param array $options
  1139. * @return array
  1140. */
  1141. protected function _maxLength($options) {
  1142. $fieldDef = $this->_introspectModel($this->model(), 'fields', $this->field());
  1143. $autoLength = (
  1144. !array_key_exists('maxlength', $options) &&
  1145. isset($fieldDef['length']) &&
  1146. is_scalar($fieldDef['length']) &&
  1147. $options['type'] !== 'select'
  1148. );
  1149. if ($autoLength &&
  1150. in_array($options['type'], array('text', 'email', 'tel', 'url', 'search'))
  1151. ) {
  1152. $options['maxlength'] = $fieldDef['length'];
  1153. }
  1154. return $options;
  1155. }
  1156. /**
  1157. * Generate div options for input
  1158. *
  1159. * @param array $options
  1160. * @return array
  1161. */
  1162. protected function _divOptions($options) {
  1163. if ($options['type'] === 'hidden') {
  1164. return array();
  1165. }
  1166. $div = $this->_extractOption('div', $options, true);
  1167. if (!$div) {
  1168. return array();
  1169. }
  1170. $divOptions = array('class' => 'input');
  1171. $divOptions = $this->addClass($divOptions, $options['type']);
  1172. if (is_string($div)) {
  1173. $divOptions['class'] = $div;
  1174. } elseif (is_array($div)) {
  1175. $divOptions = array_merge($divOptions, $div);
  1176. }
  1177. if (
  1178. $this->_extractOption('required', $options) !== false &&
  1179. $this->_introspectModel($this->model(), 'validates', $this->field())
  1180. ) {
  1181. $divOptions = $this->addClass($divOptions, 'required');
  1182. }
  1183. if (!isset($divOptions['tag'])) {
  1184. $divOptions['tag'] = 'div';
  1185. }
  1186. return $divOptions;
  1187. }
  1188. /**
  1189. * Extracts a single option from an options array.
  1190. *
  1191. * @param string $name The name of the option to pull out.
  1192. * @param array $options The array of options you want to extract.
  1193. * @param mixed $default The default option value
  1194. * @return mixed the contents of the option or default
  1195. */
  1196. protected function _extractOption($name, $options, $default = null) {
  1197. if (array_key_exists($name, $options)) {
  1198. return $options[$name];
  1199. }
  1200. return $default;
  1201. }
  1202. /**
  1203. * Generate a label for an input() call.
  1204. *
  1205. * $options can contain a hash of id overrides. These overrides will be
  1206. * used instead of the generated values if present.
  1207. *
  1208. * @param string $fieldName
  1209. * @param string $label
  1210. * @param array $options Options for the label element. 'NONE' option is deprecated and will be removed in 3.0
  1211. * @return string Generated label element
  1212. */
  1213. protected function _inputLabel($fieldName, $label, $options) {
  1214. $labelAttributes = $this->domId(array(), 'for');
  1215. $idKey = null;
  1216. if ($options['type'] === 'date' || $options['type'] === 'datetime') {
  1217. $firstInput = 'M';
  1218. if (
  1219. array_key_exists('dateFormat', $options) &&
  1220. ($options['dateFormat'] === null || $options['dateFormat'] === 'NONE')
  1221. ) {
  1222. $firstInput = 'H';
  1223. } elseif (!empty($options['dateFormat'])) {
  1224. $firstInput = substr($options['dateFormat'], 0, 1);
  1225. }
  1226. switch ($firstInput) {
  1227. case 'D':
  1228. $idKey = 'day';
  1229. $labelAttributes['for'] .= 'Day';
  1230. break;
  1231. case 'Y':
  1232. $idKey = 'year';
  1233. $labelAttributes['for'] .= 'Year';
  1234. break;
  1235. case 'M':
  1236. $idKey = 'month';
  1237. $labelAttributes['for'] .= 'Month';
  1238. break;
  1239. case 'H':
  1240. $idKey = 'hour';
  1241. $labelAttributes['for'] .= 'Hour';
  1242. }
  1243. }
  1244. if ($options['type'] === 'time') {
  1245. $labelAttributes['for'] .= 'Hour';
  1246. $idKey = 'hour';
  1247. }
  1248. if (isset($idKey) && isset($options['id']) && isset($options['id'][$idKey])) {
  1249. $labelAttributes['for'] = $options['id'][$idKey];
  1250. }
  1251. if (is_array($label)) {
  1252. $labelText = null;
  1253. if (isset($label['text'])) {
  1254. $labelText = $label['text'];
  1255. unset($label['text']);
  1256. }
  1257. $labelAttributes = array_merge($labelAttributes, $label);
  1258. } else {
  1259. $labelText = $label;
  1260. }
  1261. if (isset($options['id']) && is_string($options['id'])) {
  1262. $labelAttributes = array_merge($labelAttributes, array('for' => $options['id']));
  1263. }
  1264. return $this->label($fieldName, $labelText, $labelAttributes);
  1265. }
  1266. /**
  1267. * Creates a checkbox input widget.
  1268. *
  1269. * ### Options:
  1270. *
  1271. * - `value` - the value of the checkbox
  1272. * - `checked` - boolean indicate that this checkbox is checked.
  1273. * - `hiddenField` - boolean to indicate if you want the results of checkbox() to include
  1274. * a hidden input with a value of ''.
  1275. * - `disabled` - create a disabled input.
  1276. * - `default` - Set the default value for the checkbox. This allows you to start checkboxes
  1277. * as checked, without having to check the POST data. A matching POST data value, will overwrite
  1278. * the default value.
  1279. *
  1280. * @param string $fieldName Name of a field, like this "Modelname.fieldname"
  1281. * @param array $options Array of HTML attributes.
  1282. * @return string An HTML text input element.
  1283. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
  1284. */
  1285. public function checkbox($fieldName, $options = array()) {
  1286. $valueOptions = array();
  1287. if (isset($options['default'])) {
  1288. $valueOptions['default'] = $options['default'];
  1289. unset($options['default']);
  1290. }
  1291. $options += array('required' => false);
  1292. $options = $this->_initInputField($fieldName, $options) + array('hiddenField' => true);
  1293. $value = current($this->value($valueOptions));
  1294. $output = '';
  1295. if (empty($options['value'])) {
  1296. $options['value'] = 1;
  1297. }
  1298. if (
  1299. (!isset($options['checked']) && !empty($value) && $value == $options['value']) ||
  1300. !empty($options['checked'])
  1301. ) {
  1302. $options['checked'] = 'checked';
  1303. }
  1304. if ($options['hiddenField']) {
  1305. $hiddenOptions = array(
  1306. 'id' => $options['id'] . '_',
  1307. 'name' => $options['name'],
  1308. 'value' => ($options['hiddenField'] !== true ? $options['hiddenField'] : '0'),
  1309. 'secure' => false
  1310. );
  1311. if (isset($options['disabled']) && $options['disabled']) {
  1312. $hiddenOptions['disabled'] = 'disabled';
  1313. }
  1314. $output = $this->hidden($fieldName, $hiddenOptions);
  1315. }
  1316. unset($options['hiddenField']);
  1317. return $output . $this->Html->useTag('checkbox', $options['name'], array_diff_key($options, array('name' => null)));
  1318. }
  1319. /**
  1320. * Creates a set of radio widgets. Will create a legend and fieldset
  1321. * by default. Use $options to control this
  1322. *
  1323. * ### Attributes:
  1324. *
  1325. * - `separator` - define the string in between the radio buttons
  1326. * - `between` - the string between legend and input set or array of strings to insert
  1327. * strings between each input block
  1328. * - `legend` - control whether or not the widget set has a fieldset & legend
  1329. * - `value` - indicate a value that is should be checked
  1330. * - `label` - boolean to indicate whether or not labels for widgets show be displayed
  1331. * - `hiddenField` - boolean to indicate if you want the results of radio() to include
  1332. * a hidden input with a value of ''. This is useful for creating radio sets that non-continuous
  1333. * - `disabled` - Set to `true` or `disabled` to disable all the radio buttons.
  1334. * - `empty` - Set to `true` to create a input with the value '' as the first option. When `true`
  1335. * the radio label will be 'empty'. Set this option to a string to control the label value.
  1336. *
  1337. * @param string $fieldName Name of a field, like this "Modelname.fieldname"
  1338. * @param array $options Radio button options array.
  1339. * @param array $attributes Array of HTML attributes, and special attributes above.
  1340. * @return string Completed radio widget set.
  1341. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
  1342. */
  1343. public function radio($fieldName, $options = array(), $attributes = array()) {
  1344. $attributes = $this->_initInputField($fieldName, $attributes);
  1345. $showEmpty = $this->_extractOption('empty', $attributes);
  1346. if ($showEmpty) {
  1347. $showEmpty = ($showEmpty === true) ? __d('cake', 'empty') : $showEmpty;
  1348. $options = array('' => $showEmpty) + $options;
  1349. }
  1350. unset($attributes['empty']);
  1351. $legend = false;
  1352. if (isset($attributes['legend'])) {
  1353. $legend = $attributes['legend'];
  1354. unset($attributes['legend']);
  1355. } elseif (count($options) > 1) {
  1356. $legend = __(Inflector::humanize($this->field()));
  1357. }
  1358. $label = true;
  1359. if (isset($attributes['label'])) {
  1360. $label = $attributes['label'];
  1361. unset($attributes['label']);
  1362. }
  1363. $separator = null;
  1364. if (isset($attributes['separator'])) {
  1365. $separator = $attributes['separator'];
  1366. unset($attributes['separator']);
  1367. }
  1368. $between = null;
  1369. if (isset($attributes['between'])) {
  1370. $between = $attributes['between'];
  1371. unset($attributes['between']);
  1372. }
  1373. $value = null;
  1374. if (isset($attributes['value'])) {
  1375. $value = $attributes['value'];
  1376. } else {
  1377. $value = $this->value($fieldName);
  1378. }
  1379. $disabled = array();
  1380. if (isset($attributes['disabled'])) {
  1381. $disabled = $attributes['disabled'];
  1382. }
  1383. $out = array();
  1384. $hiddenField = isset($attributes['hiddenField']) ? $attributes['hiddenField'] : true;
  1385. unset($attributes['hiddenField']);
  1386. if (isset($value) && is_bool($value)) {
  1387. $value = $value ? 1 : 0;
  1388. }
  1389. $this->_domIdSuffixes = array();
  1390. foreach ($options as $optValue => $optTitle) {
  1391. $optionsHere = array('value' => $optValue, 'disabled' => false);
  1392. if (isset($value) && strval($optValue) === strval($value)) {
  1393. $optionsHere['checked'] = 'checked';
  1394. }
  1395. $isNumeric = is_numeric($optValue);
  1396. if ($disabled && (!is_array($disabled) || in_array((string)$optValue, $disabled, !$isNumeric))) {
  1397. $optionsHere['disabled'] = true;
  1398. }
  1399. $tagName = $attributes['id'] . $this->domIdSuffix($optValue);
  1400. if ($label) {
  1401. $labelOpts = is_array($label) ? $label : array();
  1402. $labelOpts += array('for' => $tagName);
  1403. $optTitle = $this->label($tagName, $optTitle, $labelOpts);
  1404. }
  1405. if (is_array($between)) {
  1406. $optTitle .= array_shift($between);
  1407. }
  1408. $allOptions = array_merge($attributes, $optionsHere);
  1409. $out[] = $this->Html->useTag('radio', $attributes['name'], $tagName,
  1410. array_diff_key($allOptions, array('name' => null, 'type' => null, 'id' => null)),
  1411. $optTitle
  1412. );
  1413. }
  1414. $hidden = null;
  1415. if ($hiddenField) {
  1416. if (!isset($value) || $value === '') {
  1417. $hidden = $this->hidden($fieldName, array(
  1418. 'id' => $attributes['id'] . '_', 'value' => '', 'name' => $attributes['name']
  1419. ));
  1420. }
  1421. }
  1422. $out = $hidden . implode($separator, $out);
  1423. if (is_array($between)) {
  1424. $between = '';
  1425. }
  1426. if ($legend) {
  1427. $out = $this->Html->useTag('fieldset', '', $this->Html->useTag('legend', $legend) . $between . $out);
  1428. }
  1429. return $out;
  1430. }
  1431. /**
  1432. * Missing method handler - implements various simple input types. Is used to create inputs
  1433. * of various types. e.g. `$this->Form->text();` will create `<input type="text" />` while
  1434. * `$this->Form->range();` will create `<input type="range" />`
  1435. *
  1436. * ### Usage
  1437. *
  1438. * `$this->Form->search('User.query', array('value' => 'test'));`
  1439. *
  1440. * Will make an input like:
  1441. *
  1442. * `<input type="search" id="UserQuery" name="data[User][query]" value="test" />`
  1443. *
  1444. * The first argument to an input type should always be the fieldname, in `Model.field` format.
  1445. * The second argument should always be an array of attributes for the input.
  1446. *
  1447. * @param string $method Method name / input type to make.
  1448. * @param array $params Parameters for the method call
  1449. * @return string Formatted input method.
  1450. * @throws CakeException When there are no params for the method call.
  1451. */
  1452. public function __call($method, $params) {
  1453. $options = array();
  1454. if (empty($params)) {
  1455. throw new CakeException(__d('cake_dev', 'Missing field name for FormHelper::%s', $method));
  1456. }
  1457. if (isset($params[1])) {
  1458. $options = $params[1];
  1459. }
  1460. if (!isset($options['type'])) {
  1461. $options['type'] = $method;
  1462. }
  1463. $options = $this->_initInputField($params[0], $options);
  1464. return $this->Html->useTag('input', $options['name'], array_diff_key($options, array('name' => null)));
  1465. }
  1466. /**
  1467. * Creates a textarea widget.
  1468. *
  1469. * ### Options:
  1470. *
  1471. * - `escape` - Whether or not the contents of the textarea should be escaped. Defaults to true.
  1472. *
  1473. * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
  1474. * @param array $options Array of HTML attributes, and special options above.
  1475. * @return string A generated HTML text input element
  1476. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::textarea
  1477. */
  1478. public function textarea($fieldName, $options = array()) {
  1479. $options = $this->_initInputField($fieldName, $options);
  1480. $value = null;
  1481. if (array_key_exists('value', $options)) {
  1482. $value = $options['value'];
  1483. if (!array_key_exists('escape', $options) || $options['escape'] !== false) {
  1484. $value = h($value);
  1485. }
  1486. unset($options['value']);
  1487. }
  1488. return $this->Html->useTag('textarea', $options['name'], array_diff_key($options, array('type' => null, 'name' => null)), $value);
  1489. }
  1490. /**
  1491. * Creates a hidden input field.
  1492. *
  1493. * @param string $fieldName Name of a field, in the form of "Modelname.fieldname"
  1494. * @param array $options Array of HTML attributes.
  1495. * @return string A generated hidden input
  1496. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hidden
  1497. */
  1498. public function hidden($fieldName, $options = array()) {
  1499. $options += array('required' => false, 'secure' => true);
  1500. $secure = $options['secure'];
  1501. unset($options['secure']);
  1502. $options = $this->_initInputField($fieldName, array_merge(
  1503. $options, array('secure' => self::SECURE_SKIP)
  1504. ));
  1505. if ($secure === true) {
  1506. $this->_secure(true, null, '' . $options['value']);
  1507. }
  1508. return $this->Html->useTag('hidden', $options['name'], array_diff_key($options, array('name' => null)));
  1509. }
  1510. /**
  1511. * Creates file input widget.
  1512. *
  1513. * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
  1514. * @param array $options Array of HTML attributes.
  1515. * @return string A generated file input.
  1516. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::file
  1517. */
  1518. public function file($fieldName, $options = array()) {
  1519. $options += array('secure' => true);
  1520. $secure = $options['secure'];
  1521. $options['secure'] = self::SECURE_SKIP;
  1522. $options = $this->_initInputField($fieldName, $options);
  1523. $field = $this->entity();
  1524. foreach (array('name', 'type', 'tmp_name', 'error', 'size') as $suffix) {
  1525. $this->_secure($secure, array_merge($field, array($suffix)));
  1526. }
  1527. $exclude = array('name' => null, 'value' => null);
  1528. return $this->Html->useTag('file', $options['name'], array_diff_key($options, $exclude));
  1529. }
  1530. /**
  1531. * Creates a `<button>` tag. The type attribute defaults to `type="submit"`
  1532. * You can change it to a different value by using `$options['type']`.
  1533. *
  1534. * ### Options:
  1535. *
  1536. * - `escape` - HTML entity encode the $title of the button. Defaults to false.
  1537. *
  1538. * @param string $title The button's caption. Not automatically HTML encoded
  1539. * @param array $options Array of options and HTML attributes.
  1540. * @return string A HTML button tag.
  1541. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::button
  1542. */
  1543. public function button($title, $options = array()) {
  1544. $options += array('type' => 'submit', 'escape' => false, 'secure' => false);
  1545. if ($options['escape']) {
  1546. $title = h($title);
  1547. }
  1548. if (isset($options['name'])) {
  1549. $name = str_replace(array('[', ']'), array('.', ''), $options['name']);
  1550. $this->_secure($options['secure'], $name);
  1551. }
  1552. return $this->Html->useTag('button', $options, $title);
  1553. }
  1554. /**
  1555. * Create a `<button>` tag with a surrounding `<form>` that submits via POST.
  1556. *
  1557. * This method creates a `<form>` element. So do not use this method in an already opened form.
  1558. * Instead use FormHelper::submit() or FormHelper::button() to create buttons inside opened forms.
  1559. *
  1560. * ### Options:
  1561. *
  1562. * - `data` - Array with key/value to pass in input hidden
  1563. * - Other options is the same of button method.
  1564. *
  1565. * @param string $title The button's caption. Not automatically HTML encoded
  1566. * @param string|array $url URL as string or array
  1567. * @param array $options Array of options and HTML attributes.
  1568. * @return string A HTML button tag.
  1569. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postButton
  1570. */
  1571. public function postButton($title, $url, $options = array()) {
  1572. $out = $this->create(false, array('id' => false, 'url' => $url));
  1573. if (isset($options['data']) && is_array($options['data'])) {
  1574. foreach ($options['data'] as $key => $value) {
  1575. $out .= $this->hidden($key, array('value' => $value, 'id' => false));
  1576. }
  1577. unset($options['data']);
  1578. }
  1579. $out .= $this->button($title, $options);
  1580. $out .= $this->end();
  1581. return $out;
  1582. }
  1583. /**
  1584. * Creates an HTML link, but access the URL using the method you specify (defaults to POST).
  1585. * Requires javascript to be enabled in browser.
  1586. *
  1587. * This method creates a `<form>` element. So do not use this method inside an existing form.
  1588. * Instead you should add a submit button using FormHelper::submit()
  1589. *
  1590. * ### Options:
  1591. *
  1592. * - `data` - Array with key/value to pass in input hidden
  1593. * - `method` - Request method to use. Set to 'delete' to simulate HTTP/1.1 DELETE request. Defaults to 'post'.
  1594. * - `confirm` - Can be used instead of $confirmMessage.
  1595. * - `inline` - Whether or not the associated form tag should be output inline.
  1596. * Set to false to have the form tag appended to the 'postLink' view block.
  1597. * Defaults to true.
  1598. * - `block` - Choose a custom block to append the form tag to. Using this option
  1599. * will override the inline option.
  1600. * - Other options are the same of HtmlHelper::link() method.
  1601. * - The option `onclick` will be replaced.
  1602. *
  1603. * @param string $title The content to be wrapped by <a> tags.
  1604. * @param string|array $url Cake-relative URL or array of URL parameters, or external URL (starts with http://)
  1605. * @param array $options Array of HTML attributes.
  1606. * @param boolean|string $confirmMessage JavaScript confirmation message.
  1607. * @return string An `<a />` element.
  1608. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postLink
  1609. */
  1610. public function postLink($title, $url = null, $options = array(), $confirmMessage = false) {
  1611. $options += array('inline' => true, 'block' => null);
  1612. if (!$options['inline'] && empty($options['block'])) {
  1613. $options['block'] = __FUNCTION__;
  1614. }
  1615. unset($options['inline']);
  1616. $requestMethod = 'POST';
  1617. if (!empty($options['method'])) {
  1618. $requestMethod = strtoupper($options['method']);
  1619. unset($options['method']);
  1620. }
  1621. if (!empty($options['confirm'])) {
  1622. $confirmMessage = $options['confirm'];
  1623. unset($options['confirm']);
  1624. }
  1625. $formName = str_replace('.', '', uniqid('post_', true));
  1626. $formUrl = $this->url($url);
  1627. $formOptions = array(
  1628. 'name' => $formName,
  1629. 'id' => $formName,
  1630. 'style' => 'display:none;',
  1631. 'method' => 'post',
  1632. );
  1633. if (isset($options['target'])) {
  1634. $formOptions['target'] = $options['target'];
  1635. unset($options['target']);
  1636. }
  1637. $out = $this->Html->useTag('form', $formUrl, $formOptions);
  1638. $out .= $this->Html->useTag('hidden', '_method', array(
  1639. 'value' => $requestMethod
  1640. ));
  1641. $out .= $this->_csrfField();
  1642. $fields = array();
  1643. if (isset($options['data']) && is_array($options['data'])) {
  1644. foreach ($options['data'] as $key => $value) {
  1645. $fields[$key] = $value;
  1646. $out .= $this->hidden($key, array('value' => $value, 'id' => false));
  1647. }
  1648. unset($options['data']);
  1649. }
  1650. $out .= $this->secure($fields);
  1651. $out .= $this->Html->useTag('formend');
  1652. if ($options['block']) {
  1653. $this->_View->append($options['block'], $out);
  1654. $out = '';
  1655. }
  1656. unset($options['block']);
  1657. $url = '#';
  1658. $onClick = 'document.' . $formName . '.submit();';
  1659. if ($confirmMessage) {
  1660. $options['onclick'] = $this->_confirm($confirmMessage, $onClick, '', $options);
  1661. } else {
  1662. $options['onclick'] = $onClick . ' ';
  1663. }
  1664. $options['onclick'] .= 'event.returnValue = false; return false;';
  1665. $out .= $this->Html->link($title, $url, $options);
  1666. return $out;
  1667. }
  1668. /**
  1669. * Creates a submit button element. This method will generate `<input />` elements that
  1670. * can be used to submit, and reset forms by using $options. image submits can be created by supplying an
  1671. * image path for $caption.
  1672. *
  1673. * ### Options
  1674. *
  1675. * - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to
  1676. * FormHelper::input().
  1677. * - `before` - Content to include before the input.
  1678. * - `after` - Content to include after the input.
  1679. * - `type` - Set to 'reset' for reset inputs. Defaults to 'submit'
  1680. * - Other attributes will be assigned to the input element.
  1681. *
  1682. * ### Options
  1683. *
  1684. * - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to
  1685. * FormHelper::input().
  1686. * - Other attributes will be assigned to the input element.
  1687. *
  1688. * @param string $caption The label appearing on the button OR if string contains :// or the
  1689. * extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension
  1690. * exists, AND the first character is /, image is relative to webroot,
  1691. * OR if the first character is not /, image is relative to webroot/img.
  1692. * @param array $options Array of options. See above.
  1693. * @return string A HTML submit button
  1694. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::submit
  1695. */
  1696. public function submit($caption = null, $options = array()) {
  1697. if (!is_string($caption) && empty($caption)) {
  1698. $caption = __d('cake', 'Submit');
  1699. }
  1700. $out = null;
  1701. $div = true;
  1702. if (isset($options['div'])) {
  1703. $div = $options['div'];
  1704. unset($options['div']);
  1705. }
  1706. $options += array('type' => 'submit', 'before' => null, 'after' => null, 'secure' => false);
  1707. $divOptions = array('tag' => 'div');
  1708. if ($div === true) {
  1709. $divOptions['class'] = 'submit';
  1710. } elseif ($div === false) {
  1711. unset($divOptions);
  1712. } elseif (is_string($div)) {
  1713. $divOptions['class'] = $div;
  1714. } elseif (is_array($div)) {
  1715. $divOptions = array_merge(array('class' => 'submit', 'tag' => 'div'), $div);
  1716. }
  1717. if (isset($options['name'])) {
  1718. $name = str_replace(array('[', ']'), array('.', ''), $options['name']);
  1719. $this->_secure($options['secure'], $name);
  1720. }
  1721. unset($options['secure']);
  1722. $before = $options['before'];
  1723. $after = $options['after'];
  1724. unset($options['before'], $options['after']);
  1725. $isUrl = strpos($caption, '://') !== false;
  1726. $isImage = preg_match('/\.(jpg|jpe|jpeg|gif|png|ico)$/', $caption);
  1727. if ($isUrl || $isImage) {
  1728. $unlockFields = array('x', 'y');
  1729. if (isset($options['name'])) {
  1730. $unlockFields = array(
  1731. $options['name'] . '_x', $options['name'] . '_y'
  1732. );
  1733. }
  1734. foreach ($unlockFields as $ignore) {
  1735. $this->unlockField($ignore);
  1736. }
  1737. }
  1738. if ($isUrl) {
  1739. unset($options['type']);
  1740. $tag = $this->Html->useTag('submitimage', $caption, $options);
  1741. } elseif ($isImage) {
  1742. unset($options['type']);
  1743. if ($caption{0} !== '/') {
  1744. $url = $this->webroot(Configure::read('App.imageBaseUrl') . $caption);
  1745. } else {
  1746. $url = $this->webroot(trim($caption, '/'));
  1747. }
  1748. $url = $this->assetTimestamp($url);
  1749. $tag = $this->Html->useTag('submitimage', $url, $options);
  1750. } else {
  1751. $options['value'] = $caption;
  1752. $tag = $this->Html->useTag('submit', $options);
  1753. }
  1754. $out = $before . $tag . $after;
  1755. if (isset($divOptions)) {
  1756. $tag = $divOptions['tag'];
  1757. unset($divOptions['tag']);
  1758. $out = $this->Html->tag($tag, $out, $divOptions);
  1759. }
  1760. return $out;
  1761. }
  1762. /**
  1763. * Returns a formatted SELECT element.
  1764. *
  1765. * ### Attributes:
  1766. *
  1767. * - `showParents` - If included in the array and set to true, an additional option element
  1768. * will be added for the parent of each option group. You can set an option with the same name
  1769. * and it's key will be used for the value of the option.
  1770. * - `multiple` - show a multiple select box. If set to 'checkbox' multiple checkboxes will be
  1771. * created instead.
  1772. * - `empty` - If true, the empty select option is shown. If a string,
  1773. * that string is displayed as the empty element.
  1774. * - `escape` - If true contents of options will be HTML entity encoded. Defaults to true.
  1775. * - `value` The selected value of the input.
  1776. * - `class` - When using multiple = checkbox the class name to apply to the divs. Defaults to 'checkbox'.
  1777. * - `disabled` - Control the disabled attribute. When creating a select box, set to true to disable the
  1778. * select box. When creating checkboxes, `true` will disable all checkboxes. You can also set disabled
  1779. * to a list of values you want to disable when creating checkboxes.
  1780. *
  1781. * ### Using options
  1782. *
  1783. * A simple array will create normal options:
  1784. *
  1785. * {{{
  1786. * $options = array(1 => 'one', 2 => 'two);
  1787. * $this->Form->select('Model.field', $options));
  1788. * }}}
  1789. *
  1790. * While a nested options array will create optgroups with options inside them.
  1791. * {{{
  1792. * $options = array(
  1793. * 1 => 'bill',
  1794. * 'fred' => array(
  1795. * 2 => 'fred',
  1796. * 3 => 'fred jr.'
  1797. * )
  1798. * );
  1799. * $this->Form->select('Model.field', $options);
  1800. * }}}
  1801. *
  1802. * In the above `2 => 'fred'` will not generate an option element. You should enable the `showParents`
  1803. * attribute to show the fred option.
  1804. *
  1805. * If you have multiple options that need to have the same value attribute, you can
  1806. * use an array of arrays to express this:
  1807. *
  1808. * {{{
  1809. * $options = array(
  1810. * array('name' => 'United states', 'value' => 'USA'),
  1811. * array('name' => 'USA', 'value' => 'USA'),
  1812. * );
  1813. * }}}
  1814. *
  1815. * @param string $fieldName Name attribute of the SELECT
  1816. * @param array $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the
  1817. * SELECT element
  1818. * @param array $attributes The HTML attributes of the select element.
  1819. * @return string Formatted SELECT element
  1820. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
  1821. */
  1822. public function select($fieldName, $options = array(), $attributes = array()) {
  1823. $select = array();
  1824. $style = null;
  1825. $tag = null;
  1826. $attributes += array(
  1827. 'class' => null,
  1828. 'escape' => true,
  1829. 'secure' => true,
  1830. 'empty' => '',
  1831. 'showParents' => false,
  1832. 'hiddenField' => true,
  1833. 'disabled' => false
  1834. );
  1835. $escapeOptions = $this->_extractOption('escape', $attributes);
  1836. $secure = $this->_extractOption('secure', $attributes);
  1837. $showEmpty = $this->_extractOption('empty', $attributes);
  1838. $showParents = $this->_extractOption('showParents', $attributes);
  1839. $hiddenField = $this->_extractOption('hiddenField', $attributes);
  1840. unset($attributes['escape'], $attributes['secure'], $attributes['empty'], $attributes['showParents'], $attributes['hiddenField']);
  1841. $id = $this->_extractOption('id', $attributes);
  1842. $attributes = $this->_initInputField($fieldName, array_merge(
  1843. (array)$attributes, array('secure' => self::SECURE_SKIP)
  1844. ));
  1845. if (is_string($options) && isset($this->_options[$options])) {
  1846. $options = $this->_generateOptions($options);
  1847. } elseif (!is_array($options)) {
  1848. $options = array();
  1849. }
  1850. if (isset($attributes['type'])) {
  1851. unset($attributes['type']);
  1852. }
  1853. if (!empty($attributes['multiple'])) {
  1854. $style = ($attributes['multiple'] === 'checkbox') ? 'checkbox' : null;
  1855. $template = ($style) ? 'checkboxmultiplestart' : 'selectmultiplestart';
  1856. $tag = $template;
  1857. if ($hiddenField) {
  1858. $hiddenAttributes = array(
  1859. 'value' => '',
  1860. 'id' => $attributes['id'] . ($style ? '' : '_'),
  1861. 'secure' => false,
  1862. 'name' => $attributes['name']
  1863. );
  1864. $select[] = $this->hidden(null, $hiddenAttributes);
  1865. }
  1866. } else {
  1867. $tag = 'selectstart';
  1868. }
  1869. if ($tag === 'checkboxmultiplestart') {
  1870. unset($attributes['required']);
  1871. }
  1872. if (!empty($tag) || isset($template)) {
  1873. $hasOptions = (count($options) > 0 || $showEmpty);
  1874. // Secure the field if there are options, or its a multi select.
  1875. // Single selects with no options don't submit, but multiselects do.
  1876. if (
  1877. (!isset($secure) || $secure) &&
  1878. empty($attributes['disabled']) &&
  1879. (!empty($attributes['multiple']) || $hasOptions)
  1880. ) {
  1881. $this->_secure(true, $this->_secureFieldName($attributes));
  1882. }
  1883. $select[] = $this->Html->useTag($tag, $attributes['name'], array_diff_key($attributes, array('name' => null, 'value' => null)));
  1884. }
  1885. $emptyMulti = (
  1886. $showEmpty !== null && $showEmpty !== false && !(
  1887. empty($showEmpty) && (isset($attributes) &&
  1888. array_key_exists('multiple', $attributes))
  1889. )
  1890. );
  1891. if ($emptyMulti) {
  1892. $showEmpty = ($showEmpty === true) ? '' : $showEmpty;
  1893. $options = array('' => $showEmpty) + $options;
  1894. }
  1895. if (!$id) {
  1896. $attributes['id'] = Inflector::camelize($attributes['id']);
  1897. }
  1898. $select = array_merge($select, $this->_selectOptions(
  1899. array_reverse($options, true),
  1900. array(),
  1901. $showParents,
  1902. array(
  1903. 'escape' => $escapeOptions,
  1904. 'style' => $style,
  1905. 'name' => $attributes['name'],
  1906. 'value' => $attributes['value'],
  1907. 'class' => $attributes['class'],
  1908. 'id' => $attributes['id'],
  1909. 'disabled' => $attributes['disabled'],
  1910. )
  1911. ));
  1912. $template = ($style === 'checkbox') ? 'checkboxmultipleend' : 'selectend';
  1913. $select[] = $this->Html->useTag($template);
  1914. return implode("\n", $select);
  1915. }
  1916. /**
  1917. * Generates a valid DOM ID suffix from a string.
  1918. * Also avoids collisions when multiple values are coverted to the same suffix by
  1919. * appending a numeric value.
  1920. *
  1921. * For pre-HTML5 IDs only characters like a-z 0-9 - _ are valid. HTML5 doesn't have that
  1922. * limitation, but to avoid layout issues it still filters out some sensitive chars.
  1923. *
  1924. * @param string $value The value that should be transferred into a DOM ID suffix.
  1925. * @param string $type Doctype to use. Defaults to html5. Anything else will use limited chars.
  1926. * @return string DOM ID
  1927. */
  1928. public function domIdSuffix($value, $type = 'html5') {
  1929. if ($type === 'html5') {
  1930. $value = str_replace(array('<', '>', ' ', '"', '\''), '_', $value);
  1931. } else {
  1932. $value = preg_replace('~[^\\pL\d-_]+~u', '_', $value);
  1933. }
  1934. $value = Inflector::camelize($value);
  1935. $count = 1;
  1936. $suffix = $value;
  1937. while (in_array($suffix, $this->_domIdSuffixes)) {
  1938. $suffix = $value . $count++;
  1939. }
  1940. $this->_domIdSuffixes[] = $suffix;
  1941. return $suffix;
  1942. }
  1943. /**
  1944. * Returns a SELECT element for days.
  1945. *
  1946. * ### Attributes:
  1947. *
  1948. * - `empty` - If true, the empty select option is shown. If a string,
  1949. * that string is displayed as the empty element.
  1950. * - `value` The selected value of the input.
  1951. *
  1952. * @param string $fieldName Prefix name for the SELECT element
  1953. * @param array $attributes HTML attributes for the select element
  1954. * @return string A generated day select box.
  1955. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::day
  1956. */
  1957. public function day($fieldName = null, $attributes = array()) {
  1958. $attributes += array('empty' => true, 'value' => null);
  1959. $attributes = $this->_dateTimeSelected('day', $fieldName, $attributes);
  1960. if (strlen($attributes['value']) > 2) {
  1961. $attributes['value'] = date_create($attributes['value'])->format('d');
  1962. } elseif ($attributes['value'] === false) {
  1963. $attributes['value'] = null;
  1964. }
  1965. return $this->select($fieldName . ".day", $this->_generateOptions('day'), $attributes);
  1966. }
  1967. /**
  1968. * Returns a SELECT element for years
  1969. *
  1970. * ### Attributes:
  1971. *
  1972. * - `empty` - If true, the empty select option is shown. If a string,
  1973. * that string is displayed as the empty element.
  1974. * - `orderYear` - Ordering of year values in select options.
  1975. * Possible values 'asc', 'desc'. Default 'desc'
  1976. * - `value` The selected value of the input.
  1977. *
  1978. * @param string $fieldName Prefix name for the SELECT element
  1979. * @param integer $minYear First year in sequence
  1980. * @param integer $maxYear Last year in sequence
  1981. * @param array $attributes Attribute array for the select elements.
  1982. * @return string Completed year select input
  1983. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::year
  1984. */
  1985. public function year($fieldName, $minYear = null, $maxYear = null, $attributes = array()) {
  1986. $attributes += array('empty' => true, 'value' => null);
  1987. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  1988. if (is_array($value)) {
  1989. $year = null;
  1990. extract($value);
  1991. $attributes['value'] = $year;
  1992. } else {
  1993. if (empty($value)) {
  1994. if (!$attributes['empty'] && !$maxYear) {
  1995. $attributes['value'] = 'now';
  1996. } elseif (!$attributes['empty'] && $maxYear && !$attributes['value']) {
  1997. $attributes['value'] = $maxYear;
  1998. }
  1999. } else {
  2000. $attributes['value'] = $value;
  2001. }
  2002. }
  2003. }
  2004. if (strlen($attributes['value']) > 4 || $attributes['value'] === 'now') {
  2005. $attributes['value'] = date_create($attributes['value'])->format('Y');
  2006. } elseif ($attributes['value'] === false) {
  2007. $attributes['value'] = null;
  2008. }
  2009. $yearOptions = array('value' => $attributes['value'], 'min' => $minYear, 'max' => $maxYear, 'order' => 'desc');
  2010. if (isset($attributes['orderYear'])) {
  2011. $yearOptions['order'] = $attributes['orderYear'];
  2012. unset($attributes['orderYear']);
  2013. }
  2014. return $this->select(
  2015. $fieldName . '.year', $this->_generateOptions('year', $yearOptions),
  2016. $attributes
  2017. );
  2018. }
  2019. /**
  2020. * Returns a SELECT element for months.
  2021. *
  2022. * ### Attributes:
  2023. *
  2024. * - `monthNames` - If false, 2 digit numbers will be used instead of text.
  2025. * If a array, the given array will be used.
  2026. * - `empty` - If true, the empty select option is shown. If a string,
  2027. * that string is displayed as the empty element.
  2028. * - `value` The selected value of the input.
  2029. *
  2030. * @param string $fieldName Prefix name for the SELECT element
  2031. * @param array $attributes Attributes for the select element
  2032. * @return string A generated month select dropdown.
  2033. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::month
  2034. */
  2035. public function month($fieldName, $attributes = array()) {
  2036. $attributes += array('empty' => true, 'value' => null);
  2037. $attributes = $this->_dateTimeSelected('month', $fieldName, $attributes);
  2038. if (strlen($attributes['value']) > 2) {
  2039. $attributes['value'] = date_create($attributes['value'])->format('m');
  2040. } elseif ($attributes['value'] === false) {
  2041. $attributes['value'] = null;
  2042. }
  2043. $defaults = array('monthNames' => true);
  2044. $attributes = array_merge($defaults, (array)$attributes);
  2045. $monthNames = $attributes['monthNames'];
  2046. unset($attributes['monthNames']);
  2047. return $this->select(
  2048. $fieldName . ".month",
  2049. $this->_generateOptions('month', array('monthNames' => $monthNames)),
  2050. $attributes
  2051. );
  2052. }
  2053. /**
  2054. * Returns a SELECT element for hours.
  2055. *
  2056. * ### Attributes:
  2057. *
  2058. * - `empty` - If true, the empty select option is shown. If a string,
  2059. * that string is displayed as the empty element.
  2060. * - `value` The selected value of the input.
  2061. *
  2062. * @param string $fieldName Prefix name for the SELECT element
  2063. * @param boolean $format24Hours True for 24 hours format
  2064. * @param array $attributes List of HTML attributes
  2065. * @return string Completed hour select input
  2066. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hour
  2067. */
  2068. public function hour($fieldName, $format24Hours = false, $attributes = array()) {
  2069. $attributes += array('empty' => true, 'value' => null);
  2070. $attributes = $this->_dateTimeSelected('hour', $fieldName, $attributes);
  2071. if (strlen($attributes['value']) > 2) {
  2072. $Date = new DateTime($attributes['value']);
  2073. if ($format24Hours) {
  2074. $attributes['value'] = $Date->format('H');
  2075. } else {
  2076. $attributes['value'] = $Date->format('g');
  2077. }
  2078. } elseif ($attributes['value'] === false) {
  2079. $attributes['value'] = null;
  2080. }
  2081. if ($attributes['value'] > 12 && !$format24Hours) {
  2082. $attributes['value'] -= 12;
  2083. }
  2084. if (($attributes['value'] === 0 || $attributes['value'] === '00') && !$format24Hours) {
  2085. $attributes['value'] = 12;
  2086. }
  2087. return $this->select(
  2088. $fieldName . ".hour",
  2089. $this->_generateOptions($format24Hours ? 'hour24' : 'hour'),
  2090. $attributes
  2091. );
  2092. }
  2093. /**
  2094. * Returns a SELECT element for minutes.
  2095. *
  2096. * ### Attributes:
  2097. *
  2098. * - `empty` - If true, the empty select option is shown. If a string,
  2099. * that string is displayed as the empty element.
  2100. * - `value` The selected value of the input.
  2101. *
  2102. * @param string $fieldName Prefix name for the SELECT element
  2103. * @param array $attributes Array of Attributes
  2104. * @return string Completed minute select input.
  2105. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::minute
  2106. */
  2107. public function minute($fieldName, $attributes = array()) {
  2108. $attributes += array('empty' => true, 'value' => null);
  2109. $attributes = $this->_dateTimeSelected('min', $fieldName, $attributes);
  2110. if (strlen($attributes['value']) > 2) {
  2111. $attributes['value'] = date_create($attributes['value'])->format('i');
  2112. } elseif ($attributes['value'] === false) {
  2113. $attributes['value'] = null;
  2114. }
  2115. $minuteOptions = array();
  2116. if (isset($attributes['interval'])) {
  2117. $minuteOptions['interval'] = $attributes['interval'];
  2118. unset($attributes['interval']);
  2119. }
  2120. return $this->select(
  2121. $fieldName . ".min", $this->_generateOptions('minute', $minuteOptions),
  2122. $attributes
  2123. );
  2124. }
  2125. /**
  2126. * Selects values for dateTime selects.
  2127. *
  2128. * @param string $select Name of element field. ex. 'day'
  2129. * @param string $fieldName Name of fieldName being generated ex. Model.created
  2130. * @param array $attributes Array of attributes, must contain 'empty' key.
  2131. * @return array Attributes array with currently selected value.
  2132. */
  2133. protected function _dateTimeSelected($select, $fieldName, $attributes) {
  2134. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  2135. if (is_array($value)) {
  2136. $attributes['value'] = isset($value[$select]) ? $value[$select] : null;
  2137. } else {
  2138. if (empty($value)) {
  2139. if (!$attributes['empty']) {
  2140. $attributes['value'] = 'now';
  2141. }
  2142. } else {
  2143. $attributes['value'] = $value;
  2144. }
  2145. }
  2146. }
  2147. return $attributes;
  2148. }
  2149. /**
  2150. * Returns a SELECT element for AM or PM.
  2151. *
  2152. * ### Attributes:
  2153. *
  2154. * - `empty` - If true, the empty select option is shown. If a string,
  2155. * that string is displayed as the empty element.
  2156. * - `value` The selected value of the input.
  2157. *
  2158. * @param string $fieldName Prefix name for the SELECT element
  2159. * @param array|string $attributes Array of Attributes
  2160. * @return string Completed meridian select input
  2161. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::meridian
  2162. */
  2163. public function meridian($fieldName, $attributes = array()) {
  2164. $attributes += array('empty' => true, 'value' => null);
  2165. if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
  2166. if (is_array($value)) {
  2167. $meridian = null;
  2168. extract($value);
  2169. $attributes['value'] = $meridian;
  2170. } else {
  2171. if (empty($value)) {
  2172. if (!$attributes['empty']) {
  2173. $attributes['value'] = date('a');
  2174. }
  2175. } else {
  2176. $attributes['value'] = date_create($attributes['value'])->format('a');
  2177. }
  2178. }
  2179. }
  2180. if ($attributes['value'] === false) {
  2181. $attributes['value'] = null;
  2182. }
  2183. return $this->select(
  2184. $fieldName . ".meridian", $this->_generateOptions('meridian'),
  2185. $attributes
  2186. );
  2187. }
  2188. /**
  2189. * Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
  2190. *
  2191. * ### Attributes:
  2192. *
  2193. * - `monthNames` If false, 2 digit numbers will be used instead of text.
  2194. * If a array, the given array will be used.
  2195. * - `minYear` The lowest year to use in the year select
  2196. * - `maxYear` The maximum year to use in the year select
  2197. * - `interval` The interval for the minutes select. Defaults to 1
  2198. * - `separator` The contents of the string between select elements. Defaults to '-'
  2199. * - `empty` - If true, the empty select option is shown. If a string,
  2200. * that string is displayed as the empty element.
  2201. * - `round` - Set to `up` or `down` if you want to force rounding in either direction. Defaults to null.
  2202. * - `value` | `default` The default value to be used by the input. A value in `$this->data`
  2203. * matching the field name will override this value. If no default is provided `time()` will be used.
  2204. *
  2205. * @param string $fieldName Prefix name for the SELECT element
  2206. * @param string $dateFormat DMY, MDY, YMD, or null to not generate date inputs.
  2207. * @param string $timeFormat 12, 24, or null to not generate time inputs.
  2208. * @param array|string $attributes array of Attributes
  2209. * @return string Generated set of select boxes for the date and time formats chosen.
  2210. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::dateTime
  2211. */
  2212. public function dateTime($fieldName, $dateFormat = 'DMY', $timeFormat = '12', $attributes = array()) {
  2213. $attributes += array('empty' => true, 'value' => null);
  2214. $year = $month = $day = $hour = $min = $meridian = null;
  2215. if (empty($attributes['value'])) {
  2216. $attributes = $this->value($attributes, $fieldName);
  2217. }
  2218. if ($attributes['value'] === null && $attributes['empty'] != true) {
  2219. $attributes['value'] = time();
  2220. if (!empty($attributes['maxYear']) && $attributes['maxYear'] < date('Y')) {
  2221. $attributes['value'] = strtotime(date($attributes['maxYear'] . '-m-d'));
  2222. }
  2223. }
  2224. if (!empty($attributes['value'])) {
  2225. list($year, $month, $day, $hour, $min, $meridian) = $this->_getDateTimeValue(
  2226. $attributes['value'],
  2227. $timeFormat
  2228. );
  2229. }
  2230. $defaults = array(
  2231. 'minYear' => null, 'maxYear' => null, 'separator' => '-',
  2232. 'interval' => 1, 'monthNames' => true, 'round' => null
  2233. );
  2234. $attributes = array_merge($defaults, (array)$attributes);
  2235. if (isset($attributes['minuteInterval'])) {
  2236. $attributes['interval'] = $attributes['minuteInterval'];
  2237. unset($attributes['minuteInterval']);
  2238. }
  2239. $minYear = $attributes['minYear'];
  2240. $maxYear = $attributes['maxYear'];
  2241. $separator = $attributes['separator'];
  2242. $interval = $attributes['interval'];
  2243. $monthNames = $attributes['monthNames'];
  2244. $round = $attributes['round'];
  2245. $attributes = array_diff_key($attributes, $defaults);
  2246. if (!empty($interval) && $interval > 1 && !empty($min)) {
  2247. $current = new DateTime();
  2248. if ($year !== null) {
  2249. $current->setDate($year, $month, $day);
  2250. }
  2251. if ($hour !== null) {
  2252. $current->setTime($hour, $min);
  2253. }
  2254. $changeValue = $min * (1 / $interval);
  2255. switch ($round) {
  2256. case 'up':
  2257. $changeValue = ceil($changeValue);
  2258. break;
  2259. case 'down':
  2260. $changeValue = floor($changeValue);
  2261. break;
  2262. default:
  2263. $changeValue = round($changeValue);
  2264. }
  2265. $change = ($changeValue * $interval) - $min;
  2266. $current->modify($change > 0 ? "+$change minutes" : "$change minutes");
  2267. $format = ($timeFormat == 12) ? 'Y m d h i a' : 'Y m d H i a';
  2268. $newTime = explode(' ', $current->format($format));
  2269. list($year, $month, $day, $hour, $min, $meridian) = $newTime;
  2270. }
  2271. $keys = array('Day', 'Month', 'Year', 'Hour', 'Minute', 'Meridian');
  2272. $attrs = array_fill_keys($keys, $attributes);
  2273. $hasId = isset($attributes['id']);
  2274. if ($hasId && is_array($attributes['id'])) {
  2275. // check for missing ones and build selectAttr for each element
  2276. $attributes['id'] += array(
  2277. 'month' => '',
  2278. 'year' => '',
  2279. 'day' => '',
  2280. 'hour' => '',
  2281. 'minute' => '',
  2282. 'meridian' => ''
  2283. );
  2284. foreach ($keys as $key) {
  2285. $attrs[$key]['id'] = $attributes['id'][strtolower($key)];
  2286. }
  2287. }
  2288. if ($hasId && is_string($attributes['id'])) {
  2289. // build out an array version
  2290. foreach ($keys as $key) {
  2291. $attrs[$key]['id'] = $attributes['id'] . $key;
  2292. }
  2293. }
  2294. if (is_array($attributes['empty'])) {
  2295. $attributes['empty'] += array(
  2296. 'month' => true,
  2297. 'year' => true,
  2298. 'day' => true,
  2299. 'hour' => true,
  2300. 'minute' => true,
  2301. 'meridian' => true
  2302. );
  2303. foreach ($keys as $key) {
  2304. $attrs[$key]['empty'] = $attributes['empty'][strtolower($key)];
  2305. }
  2306. }
  2307. $selects = array();
  2308. foreach (preg_split('//', $dateFormat, -1, PREG_SPLIT_NO_EMPTY) as $char) {
  2309. switch ($char) {
  2310. case 'Y':
  2311. $attrs['Year']['value'] = $year;
  2312. $selects[] = $this->year(
  2313. $fieldName, $minYear, $maxYear, $attrs['Year']
  2314. );
  2315. break;
  2316. case 'M':
  2317. $attrs['Month']['value'] = $month;
  2318. $attrs['Month']['monthNames'] = $monthNames;
  2319. $selects[] = $this->month($fieldName, $attrs['Month']);
  2320. break;
  2321. case 'D':
  2322. $attrs['Day']['value'] = $day;
  2323. $selects[] = $this->day($fieldName, $attrs['Day']);
  2324. break;
  2325. }
  2326. }
  2327. $opt = implode($separator, $selects);
  2328. $attrs['Minute']['interval'] = $interval;
  2329. switch ($timeFormat) {
  2330. case '24':
  2331. $attrs['Hour']['value'] = $hour;
  2332. $attrs['Minute']['value'] = $min;
  2333. $opt .= $this->hour($fieldName, true, $attrs['Hour']) . ':' .
  2334. $this->minute($fieldName, $attrs['Minute']);
  2335. break;
  2336. case '12':
  2337. $attrs['Hour']['value'] = $hour;
  2338. $attrs['Minute']['value'] = $min;
  2339. $attrs['Meridian']['value'] = $meridian;
  2340. $opt .= $this->hour($fieldName, false, $attrs['Hour']) . ':' .
  2341. $this->minute($fieldName, $attrs['Minute']) . ' ' .
  2342. $this->meridian($fieldName, $attrs['Meridian']);
  2343. break;
  2344. }
  2345. return $opt;
  2346. }
  2347. /**
  2348. * Parse the value for a datetime selected value
  2349. *
  2350. * @param string|array $value The selected value.
  2351. * @param integer $timeFormat The time format
  2352. * @return array Array of selected value.
  2353. */
  2354. protected function _getDateTimeValue($value, $timeFormat) {
  2355. $year = $month = $day = $hour = $min = $meridian = null;
  2356. if (is_array($value)) {
  2357. extract($value);
  2358. if ($meridian === 'pm') {
  2359. $hour += 12;
  2360. }
  2361. return array($year, $month, $day, $hour, $min, $meridian);
  2362. }
  2363. if (is_numeric($value)) {
  2364. $value = strftime('%Y-%m-%d %H:%M:%S', $value);
  2365. }
  2366. $meridian = 'am';
  2367. $pos = strpos($value, '-');
  2368. if ($pos !== false) {
  2369. $date = explode('-', $value);
  2370. $days = explode(' ', $date[2]);
  2371. $day = $days[0];
  2372. $month = $date[1];
  2373. $year = $date[0];
  2374. } else {
  2375. $days[1] = $value;
  2376. }
  2377. if (!empty($timeFormat)) {
  2378. $time = explode(':', $days[1]);
  2379. if ($time[0] >= 12) {
  2380. $meridian = 'pm';
  2381. }
  2382. $hour = $min = null;
  2383. if (isset($time[1])) {
  2384. $hour = $time[0];
  2385. $min = $time[1];
  2386. }
  2387. }
  2388. return array($year, $month, $day, $hour, $min, $meridian);
  2389. }
  2390. /**
  2391. * Gets the input field name for the current tag
  2392. *
  2393. * @param array $options
  2394. * @param string $field
  2395. * @param string $key
  2396. * @return array
  2397. */
  2398. protected function _name($options = array(), $field = null, $key = 'name') {
  2399. if ($this->requestType === 'get') {
  2400. if ($options === null) {
  2401. $options = array();
  2402. } elseif (is_string($options)) {
  2403. $field = $options;
  2404. $options = 0;
  2405. }
  2406. if (!empty($field)) {
  2407. $this->setEntity($field);
  2408. }
  2409. if (is_array($options) && isset($options[$key])) {
  2410. return $options;
  2411. }
  2412. $entity = $this->entity();
  2413. $model = $this->model();
  2414. $name = $model === $entity[0] && isset($entity[1]) ? $entity[1] : $entity[0];
  2415. $last = $entity[count($entity) - 1];
  2416. if (in_array($last, $this->_fieldSuffixes)) {
  2417. $name .= '[' . $last . ']';
  2418. }
  2419. if (is_array($options)) {
  2420. $options[$key] = $name;
  2421. return $options;
  2422. }
  2423. return $name;
  2424. }
  2425. return parent::_name($options, $field, $key);
  2426. }
  2427. /**
  2428. * Returns an array of formatted OPTION/OPTGROUP elements
  2429. *
  2430. * @param array $elements
  2431. * @param array $parents
  2432. * @param boolean $showParents
  2433. * @param array $attributes
  2434. * @return array
  2435. */
  2436. protected function _selectOptions($elements = array(), $parents = array(), $showParents = null, $attributes = array()) {
  2437. $select = array();
  2438. $attributes = array_merge(
  2439. array('escape' => true, 'style' => null, 'value' => null, 'class' => null),
  2440. $attributes
  2441. );
  2442. $selectedIsEmpty = ($attributes['value'] === '' || $attributes['value'] === null);
  2443. $selectedIsArray = is_array($attributes['value']);
  2444. $this->_domIdSuffixes = array();
  2445. foreach ($elements as $name => $title) {
  2446. $htmlOptions = array();
  2447. if (is_array($title) && (!isset($title['name']) || !isset($title['value']))) {
  2448. if (!empty($name)) {
  2449. if ($attributes['style'] === 'checkbox') {
  2450. $select[] = $this->Html->useTag('fieldsetend');
  2451. } else {
  2452. $select[] = $this->Html->useTag('optiongroupend');
  2453. }
  2454. $parents[] = $name;
  2455. }
  2456. $select = array_merge($select, $this->_selectOptions(
  2457. $title, $parents, $showParents, $attributes
  2458. ));
  2459. if (!empty($name)) {
  2460. $name = $attributes['escape'] ? h($name) : $name;
  2461. if ($attributes['style'] === 'checkbox') {
  2462. $select[] = $this->Html->useTag('fieldsetstart', $name);
  2463. } else {
  2464. $select[] = $this->Html->useTag('optiongroup', $name, '');
  2465. }
  2466. }
  2467. $name = null;
  2468. } elseif (is_array($title)) {
  2469. $htmlOptions = $title;
  2470. $name = $title['value'];
  2471. $title = $title['name'];
  2472. unset($htmlOptions['name'], $htmlOptions['value']);
  2473. }
  2474. if ($name !== null) {
  2475. $isNumeric = is_numeric($name);
  2476. if (
  2477. (!$selectedIsArray && !$selectedIsEmpty && (string)$attributes['value'] == (string)$name) ||
  2478. ($selectedIsArray && in_array((string)$name, $attributes['value'], !$isNumeric))
  2479. ) {
  2480. if ($attributes['style'] === 'checkbox') {
  2481. $htmlOptions['checked'] = true;
  2482. } else {
  2483. $htmlOptions['selected'] = 'selected';
  2484. }
  2485. }
  2486. if ($showParents || (!in_array($title, $parents))) {
  2487. $title = ($attributes['escape']) ? h($title) : $title;
  2488. $hasDisabled = !empty($attributes['disabled']);
  2489. if ($hasDisabled) {
  2490. $disabledIsArray = is_array($attributes['disabled']);
  2491. if ($disabledIsArray) {
  2492. $disabledIsNumeric = is_numeric($name);
  2493. }
  2494. }
  2495. if (
  2496. $hasDisabled &&
  2497. $disabledIsArray &&
  2498. in_array((string)$name, $attributes['disabled'], !$disabledIsNumeric)
  2499. ) {
  2500. $htmlOptions['disabled'] = 'disabled';
  2501. }
  2502. if ($hasDisabled && !$disabledIsArray && $attributes['style'] === 'checkbox') {
  2503. $htmlOptions['disabled'] = $attributes['disabled'] === true ? 'disabled' : $attributes['disabled'];
  2504. }
  2505. if ($attributes['style'] === 'checkbox') {
  2506. $htmlOptions['value'] = $name;
  2507. $tagName = $attributes['id'] . $this->domIdSuffix($name);
  2508. $htmlOptions['id'] = $tagName;
  2509. $label = array('for' => $tagName);
  2510. if (isset($htmlOptions['checked']) && $htmlOptions['checked'] === true) {
  2511. $label['class'] = 'selected';
  2512. }
  2513. $name = $attributes['name'];
  2514. if (empty($attributes['class'])) {
  2515. $attributes['class'] = 'checkbox';
  2516. } elseif ($attributes['class'] === 'form-error') {
  2517. $attributes['class'] = 'checkbox ' . $attributes['class'];
  2518. }
  2519. $label = $this->label(null, $title, $label);
  2520. $item = $this->Html->useTag('checkboxmultiple', $name, $htmlOptions);
  2521. $select[] = $this->Html->div($attributes['class'], $item . $label);
  2522. } else {
  2523. if ($attributes['escape']) {
  2524. $name = h($name);
  2525. }
  2526. $select[] = $this->Html->useTag('selectoption', $name, $htmlOptions, $title);
  2527. }
  2528. }
  2529. }
  2530. }
  2531. return array_reverse($select, true);
  2532. }
  2533. /**
  2534. * Generates option lists for common <select /> menus
  2535. *
  2536. * @param string $name
  2537. * @param array $options
  2538. * @return array
  2539. */
  2540. protected function _generateOptions($name, $options = array()) {
  2541. if (!empty($this->options[$name])) {
  2542. return $this->options[$name];
  2543. }
  2544. $data = array();
  2545. switch ($name) {
  2546. case 'minute':
  2547. if (isset($options['interval'])) {
  2548. $interval = $options['interval'];
  2549. } else {
  2550. $interval = 1;
  2551. }
  2552. $i = 0;
  2553. while ($i < 60) {
  2554. $data[sprintf('%02d', $i)] = sprintf('%02d', $i);
  2555. $i += $interval;
  2556. }
  2557. break;
  2558. case 'hour':
  2559. for ($i = 1; $i <= 12; $i++) {
  2560. $data[sprintf('%02d', $i)] = $i;
  2561. }
  2562. break;
  2563. case 'hour24':
  2564. for ($i = 0; $i <= 23; $i++) {
  2565. $data[sprintf('%02d', $i)] = $i;
  2566. }
  2567. break;
  2568. case 'meridian':
  2569. $data = array('am' => 'am', 'pm' => 'pm');
  2570. break;
  2571. case 'day':
  2572. $min = 1;
  2573. $max = 31;
  2574. if (isset($options['min'])) {
  2575. $min = $options['min'];
  2576. }
  2577. if (isset($options['max'])) {
  2578. $max = $options['max'];
  2579. }
  2580. for ($i = $min; $i <= $max; $i++) {
  2581. $data[sprintf('%02d', $i)] = $i;
  2582. }
  2583. break;
  2584. case 'month':
  2585. if ($options['monthNames'] === true) {
  2586. $data['01'] = __d('cake', 'January');
  2587. $data['02'] = __d('cake', 'February');
  2588. $data['03'] = __d('cake', 'March');
  2589. $data['04'] = __d('cake', 'April');
  2590. $data['05'] = __d('cake', 'May');
  2591. $data['06'] = __d('cake', 'June');
  2592. $data['07'] = __d('cake', 'July');
  2593. $data['08'] = __d('cake', 'August');
  2594. $data['09'] = __d('cake', 'September');
  2595. $data['10'] = __d('cake', 'October');
  2596. $data['11'] = __d('cake', 'November');
  2597. $data['12'] = __d('cake', 'December');
  2598. } elseif (is_array($options['monthNames'])) {
  2599. $data = $options['monthNames'];
  2600. } else {
  2601. for ($m = 1; $m <= 12; $m++) {
  2602. $data[sprintf("%02s", $m)] = strftime("%m", mktime(1, 1, 1, $m, 1, 1999));
  2603. }
  2604. }
  2605. break;
  2606. case 'year':
  2607. $current = intval(date('Y'));
  2608. $min = !isset($options['min']) ? $current - 20 : (int)$options['min'];
  2609. $max = !isset($options['max']) ? $current + 20 : (int)$options['max'];
  2610. if ($min > $max) {
  2611. list($min, $max) = array($max, $min);
  2612. }
  2613. if (
  2614. !empty($options['value']) &&
  2615. (int)$options['value'] < $min &&
  2616. (int)$options['value'] > 0
  2617. ) {
  2618. $min = (int)$options['value'];
  2619. } elseif (!empty($options['value']) && (int)$options['value'] > $max) {
  2620. $max = (int)$options['value'];
  2621. }
  2622. for ($i = $min; $i <= $max; $i++) {
  2623. $data[$i] = $i;
  2624. }
  2625. if ($options['order'] !== 'asc') {
  2626. $data = array_reverse($data, true);
  2627. }
  2628. break;
  2629. }
  2630. $this->_options[$name] = $data;
  2631. return $this->_options[$name];
  2632. }
  2633. /**
  2634. * Sets field defaults and adds field to form security input hash.
  2635. * Will also add a 'form-error' class if the field contains validation errors.
  2636. *
  2637. * ### Options
  2638. *
  2639. * - `secure` - boolean whether or not the field should be added to the security fields.
  2640. * Disabling the field using the `disabled` option, will also omit the field from being
  2641. * part of the hashed key.
  2642. *
  2643. * This method will convert a numerically indexed 'disabled' into a associative
  2644. * value. FormHelper's internals expect associative options.
  2645. *
  2646. * @param string $field Name of the field to initialize options for.
  2647. * @param array $options Array of options to append options into.
  2648. * @return array Array of options for the input.
  2649. */
  2650. protected function _initInputField($field, $options = array()) {
  2651. if (isset($options['secure'])) {
  2652. $secure = $options['secure'];
  2653. unset($options['secure']);
  2654. } else {
  2655. $secure = (isset($this->request['_Token']) && !empty($this->request['_Token']));
  2656. }
  2657. $disabledIndex = array_search('disabled', $options, true);
  2658. if (is_int($disabledIndex)) {
  2659. unset($options[$disabledIndex]);
  2660. $options['disabled'] = true;
  2661. }
  2662. $result = parent::_initInputField($field, $options);
  2663. if ($this->tagIsInvalid() !== false) {
  2664. $result = $this->addClass($result, 'form-error');
  2665. }
  2666. if (!empty($result['disabled'])) {
  2667. return $result;
  2668. }
  2669. if (!isset($result['required']) &&
  2670. $this->_introspectModel($this->model(), 'validates', $this->field())
  2671. ) {
  2672. $result['required'] = true;
  2673. }
  2674. if ($secure === self::SECURE_SKIP) {
  2675. return $result;
  2676. }
  2677. $this->_secure($secure, $this->_secureFieldName($options));
  2678. return $result;
  2679. }
  2680. /**
  2681. * Get the field name for use with _secure().
  2682. *
  2683. * Parses the name attribute to create a dot separated name value for use
  2684. * in secured field hash.
  2685. *
  2686. * @param array $options An array of options possibly containing a name key.
  2687. * @return string|null
  2688. */
  2689. protected function _secureFieldName($options) {
  2690. if (isset($options['name'])) {
  2691. preg_match_all('/\[(.*?)\]/', $options['name'], $matches);
  2692. if (isset($matches[1])) {
  2693. return $matches[1];
  2694. }
  2695. }
  2696. return null;
  2697. }
  2698. /**
  2699. * Set/Get inputDefaults for form elements
  2700. *
  2701. * @param array $defaults New default values
  2702. * @param boolean Merge with current defaults
  2703. * @return array inputDefaults
  2704. */
  2705. public function inputDefaults($defaults = null, $merge = false) {
  2706. if ($defaults !== null) {
  2707. if ($merge) {
  2708. $this->_inputDefaults = array_merge($this->_inputDefaults, (array)$defaults);
  2709. } else {
  2710. $this->_inputDefaults = (array)$defaults;
  2711. }
  2712. }
  2713. return $this->_inputDefaults;
  2714. }
  2715. }