FormHelper.php 85 KB

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