FormHelper.php 75 KB

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