FormHelper.php 93 KB

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