FormHelper.php 95 KB

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