FormHelper.php 83 KB

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