FormHelper.php 71 KB

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