FormHelper.php 95 KB

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