FormHelper.php 84 KB

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