FormHelper.php 70 KB

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