FormHelper.php 90 KB

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