FormHelper.php 84 KB

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