FormHelper.php 78 KB

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