FormHelper.php 90 KB

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