FormHelper.php 78 KB

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