FormHelper.php 78 KB

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