FormHelper.php 90 KB

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