FormHelper.php 94 KB

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