FormHelper.php 93 KB

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