FormHelper.php 88 KB

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