FormHelper.php 93 KB

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