FormHelper.php 95 KB

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