FormHelper.php 88 KB

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