FormHelper.php 91 KB

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