FormHelper.php 90 KB

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