FormHelper.php 85 KB

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