FormHelper.php 71 KB

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