FormHelper.php 76 KB

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