FormHelper.php 74 KB

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