FormHelper.php 91 KB

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