FormHelper.php 84 KB

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