FormExtHelper.php 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  1. <?php
  2. //App::import('Helper', 'Tools.Form');
  3. App::uses('FormHelper', 'View/Helper');
  4. /**
  5. * Enhance Forms with JS widget stuff
  6. * TODO: namespace change: make it HtmlHelper
  7. *
  8. * FormExtHelper
  9. * 2011-03-07 ms
  10. */
  11. class FormExtHelper extends FormHelper { // Maybe FormHelper itself some day?
  12. public $helpers = array('Html', 'Js', 'Tools.Common');
  13. public $settings = array(
  14. 'webroot' => true # false => tools plugin
  15. );
  16. public $scriptsAdded = array(
  17. 'date' => false,
  18. 'time' => false,
  19. 'maxLength' => false,
  20. 'autoComplete' => false
  21. );
  22. public function __construct($View = null, $settings = array()) {
  23. if (($webroot = Configure::read('Asset.webroot')) !== null) {
  24. $this->settings['webroot'] = $webroot;
  25. }
  26. parent::__construct($View, $settings);
  27. }
  28. /**
  29. * Creates an HTML link, but accesses the url using DELETE method.
  30. * Requires javascript to be enabled in browser.
  31. *
  32. * This method creates a `<form>` element. So do not use this method inside an existing form.
  33. * Instead you should add a submit button using FormHelper::submit()
  34. *
  35. * ### Options:
  36. *
  37. * - `data` - Array with key/value to pass in input hidden
  38. * - `confirm` - Can be used instead of $confirmMessage.
  39. * - Other options is the same of HtmlHelper::link() method.
  40. * - The option `onclick` will be replaced.
  41. *
  42. * @param string $title The content to be wrapped by <a> tags.
  43. * @param string|array $url Cake-relative URL or array of URL parameters, or external URL (starts with http://)
  44. * @param array $options Array of HTML attributes.
  45. * @param string $confirmMessage JavaScript confirmation message.
  46. * @return string An `<a />` element.
  47. */
  48. public function deleteLink($title, $url = null, $options = array(), $confirmMessage = false) {
  49. $options['method'] = 'DELETE';
  50. return $this->postLink($title, $url, $options, $confirmMessage);
  51. }
  52. /**
  53. * Creates a textarea widget.
  54. *
  55. * ### Options:
  56. *
  57. * - `escape` - Whether or not the contents of the textarea should be escaped. Defaults to true.
  58. *
  59. * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
  60. * @param array $options Array of HTML attributes, and special options above.
  61. * @return string A generated HTML text input element
  62. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::textarea
  63. */
  64. public function textarea($fieldName, $options = array()) {
  65. $options['normalize'] = false;
  66. return parent::textarea($fieldName, $options);
  67. }
  68. /**
  69. * fix for required adding (only manually)
  70. * 2011-11-01 ms
  71. */
  72. protected function _introspectModel($model, $key, $field = null) {
  73. if ($key === 'validates' && Configure::read('Validation.autoRequire') === false) {
  74. return false;
  75. }
  76. return parent::_introspectModel($model, $key, $field);
  77. }
  78. public function postLink($title, $url = null, $options = array(), $confirmMessage = false) {
  79. if (!isset($options['class'])) {
  80. $options['class'] = 'postLink';
  81. }
  82. return parent::postLink($title, $url , $options, $confirmMessage);
  83. }
  84. /**
  85. * Generates a form input element complete with label and wrapper div
  86. * HTML 5 ready!
  87. *
  88. * ### Options
  89. *
  90. * See each field type method for more information. Any options that are part of
  91. * $attributes or $options for the different **type** methods can be included in `$options` for input().
  92. *
  93. * - `type` - Force the type of widget you want. e.g. `type => 'select'`
  94. * - `label` - Either a string label, or an array of options for the label. See FormHelper::label()
  95. * - `div` - Either `false` to disable the div, or an array of options for the div.
  96. * See HtmlHelper::div() for more options.
  97. * - `options` - for widgets that take options e.g. radio, select
  98. * - `error` - control the error message that is produced
  99. * - `empty` - String or boolean to enable empty select box options.
  100. * - `before` - Content to place before the label + input.
  101. * - `after` - Content to place after the label + input.
  102. * - `between` - Content to place between the label + input.
  103. * - `format` - format template for element order. Any element that is not in the array, will not be in the output.
  104. * - Default input format order: array('before', 'label', 'between', 'input', 'after', 'error')
  105. * - Default checkbox format order: array('before', 'input', 'between', 'label', 'after', 'error')
  106. * - Hidden input will not be formatted
  107. * - Radio buttons cannot have the order of input and label elements controlled with these settings.
  108. *
  109. * @param string $fieldName This should be "Modelname.fieldname"
  110. * @param array $options Each type of input takes different options.
  111. * @return string Completed form widget.
  112. * @access public
  113. * @link http://book.cakephp.org/view/1390/Automagic-Form-Elements
  114. */
  115. public function inputExt($fieldName, $options = array()) {
  116. //$this->setEntity($fieldName);
  117. $options = array_merge(
  118. array('before' => null, 'between' => null, 'after' => null, 'format' => null),
  119. $this->_inputDefaults,
  120. $options
  121. );
  122. $modelKey = $this->model();
  123. $fieldKey = $this->field();
  124. if (!isset($this->fieldset[$modelKey])) {
  125. $this->_introspectModel($modelKey);
  126. }
  127. if (!isset($options['type'])) {
  128. $magicType = true;
  129. $options['type'] = 'text';
  130. if (isset($options['options'])) {
  131. $options['type'] = 'select';
  132. } elseif (in_array($fieldKey, array('color', 'email', 'number', 'range', 'url'))) {
  133. $options['type'] = $fieldKey;
  134. } elseif (in_array($fieldKey, array('psword', 'passwd', 'password'))) {
  135. $options['type'] = 'password';
  136. } elseif (isset($this->fieldset[$modelKey]['fields'][$fieldKey])) {
  137. $fieldDef = $this->fieldset[$modelKey]['fields'][$fieldKey];
  138. $type = $fieldDef['type'];
  139. $primaryKey = $this->fieldset[$modelKey]['key'];
  140. }
  141. if (isset($type)) {
  142. $map = array(
  143. 'string' => 'text', 'datetime' => 'datetime', 'boolean' => 'checkbox',
  144. 'timestamp' => 'datetime', 'text' => 'textarea', 'time' => 'time',
  145. 'date' => 'date', 'float' => 'text', 'integer' => 'number',
  146. );
  147. if (isset($this->map[$type])) {
  148. $options['type'] = $this->map[$type];
  149. } elseif (isset($map[$type])) {
  150. $options['type'] = $map[$type];
  151. }
  152. if ($fieldKey == $primaryKey) {
  153. $options['type'] = 'hidden';
  154. }
  155. }
  156. if (preg_match('/_id$/', $fieldKey) && $options['type'] !== 'hidden') {
  157. $options['type'] = 'select';
  158. }
  159. if ($modelKey === $fieldKey) {
  160. $options['type'] = 'select';
  161. if (!isset($options['multiple'])) {
  162. $options['multiple'] = 'multiple';
  163. }
  164. }
  165. }
  166. $types = array('checkbox', 'radio', 'select');
  167. if (
  168. (!isset($options['options']) && in_array($options['type'], $types)) ||
  169. (isset($magicType) && $options['type'] == 'text')
  170. ) {
  171. $varName = Inflector::variable(
  172. Inflector::pluralize(preg_replace('/_id$/', '', $fieldKey))
  173. );
  174. $varOptions = $this->_View->getVar($varName);
  175. if (is_array($varOptions)) {
  176. if ($options['type'] !== 'radio') {
  177. $options['type'] = 'select';
  178. }
  179. $options['options'] = $varOptions;
  180. }
  181. }
  182. $autoLength = (!array_key_exists('maxlength', $options) && isset($fieldDef['length']));
  183. if ($autoLength && $options['type'] == 'text') {
  184. $options['maxlength'] = $fieldDef['length'];
  185. }
  186. if ($autoLength && $fieldDef['type'] == 'float') {
  187. $options['maxlength'] = array_sum(explode(',', $fieldDef['length']))+1;
  188. }
  189. $divOptions = array();
  190. $div = $this->_extractOption('div', $options, true);
  191. unset($options['div']);
  192. if (!empty($div)) {
  193. $divOptions['class'] = 'input';
  194. $divOptions = $this->addClass($divOptions, $options['type']);
  195. if (is_string($div)) {
  196. $divOptions['class'] = $div;
  197. } elseif (is_array($div)) {
  198. $divOptions = array_merge($divOptions, $div);
  199. }
  200. if (
  201. isset($this->fieldset[$modelKey]) &&
  202. in_array($fieldKey, $this->fieldset[$modelKey]['validates'])
  203. ) {
  204. $divOptions = $this->addClass($divOptions, 'required');
  205. }
  206. if (!isset($divOptions['tag'])) {
  207. $divOptions['tag'] = 'div';
  208. }
  209. }
  210. $label = null;
  211. if (isset($options['label']) && $options['type'] !== 'radio') {
  212. $label = $options['label'];
  213. unset($options['label']);
  214. }
  215. if ($options['type'] === 'radio') {
  216. $label = false;
  217. if (isset($options['options'])) {
  218. $radioOptions = (array)$options['options'];
  219. unset($options['options']);
  220. }
  221. }
  222. if ($label !== false) {
  223. $label = $this->_inputLabel($fieldName, $label, $options);
  224. }
  225. $error = $this->_extractOption('error', $options, null);
  226. unset($options['error']);
  227. $selected = $this->_extractOption('selected', $options, null);
  228. unset($options['selected']);
  229. if (isset($options['rows']) || isset($options['cols'])) {
  230. $options['type'] = 'textarea';
  231. }
  232. if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time' || $options['type'] === 'select') {
  233. $options += array('empty' => false);
  234. }
  235. if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time') {
  236. $dateFormat = $this->_extractOption('dateFormat', $options, 'MDY');
  237. $timeFormat = $this->_extractOption('timeFormat', $options, 12);
  238. unset($options['dateFormat'], $options['timeFormat']);
  239. }
  240. if ($options['type'] === 'email') {
  241. }
  242. $type = $options['type'];
  243. $out = array_merge(
  244. array('before' => null, 'label' => null, 'between' => null, 'input' => null, 'after' => null, 'error' => null),
  245. array('before' => $options['before'], 'label' => $label, 'between' => $options['between'], 'after' => $options['after'])
  246. );
  247. $format = null;
  248. if (is_array($options['format']) && in_array('input', $options['format'])) {
  249. $format = $options['format'];
  250. }
  251. unset($options['type'], $options['before'], $options['between'], $options['after'], $options['format']);
  252. switch ($type) {
  253. case 'hidden':
  254. $input = $this->hidden($fieldName, $options);
  255. $format = array('input');
  256. unset($divOptions);
  257. break;
  258. case 'checkbox':
  259. $input = $this->checkbox($fieldName, $options);
  260. $format = $format ? $format : array('before', 'input', 'between', 'label', 'after', 'error');
  261. break;
  262. case 'radio':
  263. $input = $this->radio($fieldName, $radioOptions, $options);
  264. break;
  265. case 'select':
  266. $options += array('options' => array());
  267. $list = $options['options'];
  268. unset($options['options']);
  269. $input = $this->select($fieldName, $list, $selected, $options);
  270. break;
  271. case 'time':
  272. $input = $this->dateTime($fieldName, null, $timeFormat, $selected, $options);
  273. break;
  274. case 'date':
  275. $input = $this->dateTime($fieldName, $dateFormat, null, $selected, $options);
  276. break;
  277. case 'datetime':
  278. $input = $this->dateTime($fieldName, $dateFormat, $timeFormat, $selected, $options);
  279. break;
  280. case 'textarea':
  281. $input = $this->textarea($fieldName, $options + array('cols' => '30', 'rows' => '6'));
  282. break;
  283. case 'password':
  284. case 'file':
  285. $input = $this->{$type}($fieldName, $options);
  286. break;
  287. default:
  288. $options['type'] = $type;
  289. $input = $this->text($fieldName, $options);
  290. }
  291. if ($type != 'hidden' && $error !== false) {
  292. $errMsg = $this->error($fieldName, $error);
  293. if ($errMsg) {
  294. $divOptions = $this->addClass($divOptions, 'error');
  295. $out['error'] = $errMsg;
  296. }
  297. }
  298. $out['input'] = $input;
  299. $format = $format ? $format : array('before', 'label', 'between', 'input', 'after', 'error');
  300. $output = '';
  301. foreach ($format as $element) {
  302. $output .= $out[$element];
  303. unset($out[$element]);
  304. }
  305. if (!empty($divOptions['tag'])) {
  306. $tag = $divOptions['tag'];
  307. unset($divOptions['tag']);
  308. $output = $this->Html->tag($tag, $output, $divOptions);
  309. }
  310. return $output;
  311. }
  312. /**
  313. * override with some custom functionality
  314. * - html5 list/datalist (fallback = invisible)
  315. * 2011-07-16 ms
  316. */
  317. public function input($fieldName, $options = array()) {
  318. $this->setEntity($fieldName);
  319. $modelKey = $this->model();
  320. $fieldKey = $this->field();
  321. if (isset($options['datalist'])) {
  322. $options['autocomplete'] = 'off';
  323. if (!isset($options['list'])) {
  324. $options['list'] = ucfirst($fieldKey).'List';
  325. }
  326. $datalist = $options['datalist'];
  327. $list = '<datalist id="'.$options['list'].'">';
  328. //$list .= '<!--[if IE]><div style="display: none"><![endif]-->';
  329. foreach ($datalist as $key => $val) {
  330. if (!isset($options['escape']) || $options['escape'] !== false) {
  331. $key = h($key);
  332. $val = h($val);
  333. }
  334. $list .= '<option label="'.$val.'" value="'.$key.'"></option>';
  335. }
  336. //$list .= '<!--[if IE]></div><![endif]-->';
  337. $list .= '</datalist>';
  338. unset($options['datalist']);
  339. $options['after'] = !empty($options['after']) ? $options['after'].$list : $list;
  340. }
  341. if (isset($options['required'])) {
  342. $this->_introspectModel($modelKey, 'validates', $fieldKey);
  343. $this->fieldset[$modelKey]['validates'][$fieldKey] = $options['required'];
  344. if ($options['required'] === false) {
  345. $autoRequire = Configure::read('Validation.autoRequire');
  346. Configure::write('Validation.autoRequire', false);
  347. }
  348. //unset($options['require']);
  349. }
  350. if (Configure::read('Validation.browserAutoRequire') !== true) {
  351. if (!empty($options['required'])) {
  352. //$options['div']['class'] = !empty($options['div']['class']) ? $options['div']['class'].' required' : 'required';
  353. //$options['class'] = $this->addClass(isset($options['class'])?$options['class']:array(), 'required');
  354. /*
  355. $this->setEntity($fieldName);
  356. $modelKey = $this->model();
  357. $fieldKey = $this->field();
  358. $this->fieldset[$modelKey]['validates'][$fieldKey] = true;
  359. */
  360. }
  361. if (isset($options['required'])) {
  362. unset($options['required']);
  363. }
  364. }
  365. $res = parent::input($fieldName, $options);
  366. if (isset($autoRequire)) {
  367. Configure::write('Validation.autoRequire', $autoRequire);
  368. }
  369. return $res;
  370. }
  371. /** date(time) **/
  372. //TODO: use http://trentrichardson.com/examples/timepicker/
  373. // or maybe: http://pttimeselect.sourceforge.net/example/index.html (if 24 hour + select dropdowns are supported)
  374. /**
  375. * quicklinks: clear, today, ...
  376. * 2011-04-29 ms
  377. */
  378. public function dateScripts($scripts = array(), $quicklinks = false) {
  379. foreach ($scripts as $script) {
  380. if (!$this->scriptsAdded[$script]) {
  381. switch ($script) {
  382. case 'date':
  383. if ($this->settings['webroot']) {
  384. $this->Html->script('datepicker/lang/de', false);
  385. $this->Html->script('datepicker/datepicker', false);
  386. $this->Html->css('common/datepicker', null, array('inline'=>false));
  387. } else {
  388. $this->Common->script(array('Tools.Js|datepicker/lang/de', 'Tools.Js|datepicker/datepicker'), false);
  389. $this->Common->css(array('Tools.Js|datepicker/datepicker'), null, array('inline'=>false));
  390. }
  391. $this->scriptsAdded['date'] = true;
  392. break;
  393. case 'time':
  394. continue;
  395. if ($this->settings['webroot']) {
  396. } else {
  397. //'Tools.Jquery|ui/core/jquery.ui.core', 'Tools.Jquery|ui/core/jquery.ui.widget', 'Tools.Jquery|ui/widgets/jquery.ui.slider',
  398. $this->Common->script(array('Tools.Jquery|plugins/jquery.timepicker.core', 'Tools.Jquery|plugins/jquery.timepicker'), false);
  399. $this->Common->css(array('Tools.Jquery|ui/core/jquery.ui', 'Tools.Jquery|plugins/jquery.timepicker'), null, array('inline'=>false));
  400. }
  401. break;
  402. default:
  403. break;
  404. }
  405. if ($quicklinks) {
  406. }
  407. }
  408. }
  409. }
  410. public function dateTimeExt($field, $options = array()) {
  411. $res = array();
  412. if (!isset($options['separator'])) {
  413. $options['separator'] = null;
  414. }
  415. if (!isset($options['label'])) {
  416. $options['label'] = null;
  417. }
  418. if (strpos($field, '.') !== false) {
  419. list($model, $field) = explode('.', $field, 2);
  420. } else {
  421. $entity = $this->entity();
  422. $model = $this->model();
  423. }
  424. $defaultOptions = array(
  425. 'empty' => false,
  426. 'return' => true,
  427. );
  428. $customOptions = array_merge($defaultOptions, $options);
  429. $res[] = $this->date($field, $customOptions);
  430. $res[] = $this->time($field, $customOptions);
  431. $select = implode(' &nbsp; ', $res);
  432. //return $this->date($field, $options).$select;
  433. if ($this->isFieldError($field)) {
  434. $error = $this->error($field);
  435. } else {
  436. $error = '';
  437. }
  438. $fieldname = Inflector::camelize($field);
  439. $script = '
  440. <script type="text/javascript">
  441. // <![CDATA[
  442. var opts = {
  443. formElements:{"'.$model.$fieldname.'":"Y","'.$model.$fieldname.'-mm":"m","'.$model.$fieldname.'-dd":"d"},
  444. showWeeks:true,
  445. statusFormat:"l-cc-sp-d-sp-F-sp-Y",
  446. // Position the button within a wrapper span with an id of "button-wrapper"
  447. positioned:"button-wrapper"
  448. };
  449. datePickerController.createDatePicker(opts);
  450. // ]]>
  451. </script>
  452. ';
  453. return '<div class="input date'.(!empty($error)?' error':'').'">'.$this->label($model.'.'.$field, $options['label']).''.$select.''.$error.'</div>'.$script;
  454. }
  455. /**
  456. * @deprecated
  457. * use Form::dateExt
  458. */
  459. public function date($field, $options = array()) {
  460. return $this->dateExt($field, $options);
  461. }
  462. /**
  463. * date input (day, month, year) + js
  464. * @see http://www.frequency-decoder.com/2006/10/02/unobtrusive-date-picker-widgit-update/
  465. * @param field (field or Model.field)
  466. * @param options
  467. * - separator (between day, month, year)
  468. * - label
  469. * - empty
  470. * - disableDays (TODO!)
  471. * - minYear/maxYear (TODO!) / rangeLow/rangeHigh (xxxx-xx-xx or today)
  472. * 2010-01-20 ms
  473. */
  474. public function dateExt($field, $options = array()) {
  475. $return = false;
  476. if (isset($options['return'])) {
  477. $return = $options['return'];
  478. unset($options['return']);
  479. }
  480. $quicklinks = false;
  481. if (isset($options['quicklinks'])) {
  482. $quicklinks = $options['quicklinks'];
  483. unset($options['quicklinks']);
  484. }
  485. if (isset($options['callbacks'])) {
  486. $callbacks = $options['callbacks'];
  487. unset($options['callbacks']);
  488. }
  489. $this->dateScripts(array('date'), $quicklinks);
  490. $res = array();
  491. if (!isset($options['separator'])) {
  492. $options['separator'] = '-';
  493. }
  494. if (!isset($options['label'])) {
  495. $options['label'] = null;
  496. }
  497. if (isset($options['disableDays'])) {
  498. $disableDays = $options['disableDays'];
  499. }
  500. if (isset($options['highligtDays'])) {
  501. $highligtDays = $options['highligtDays'];
  502. } else {
  503. $highligtDays = '67';
  504. }
  505. if (strpos($field, '.') !== false) {
  506. list($modelName, $fieldName) = explode('.', $field, 2);
  507. } else {
  508. $entity = $this->entity();
  509. $modelName = $this->model();
  510. $fieldName = $field;
  511. }
  512. $defaultOptions = array(
  513. 'empty' => false,
  514. 'minYear' => date('Y')-10,
  515. 'maxYear' => date('Y')+10
  516. );
  517. $defaultOptions = array_merge($defaultOptions, (array)Configure::read('Form.date'));
  518. $fieldName = Inflector::camelize($fieldName);
  519. $customOptions = array(
  520. 'id' => $modelName.$fieldName.'-dd',
  521. 'class' => 'day'
  522. );
  523. $customOptions = array_merge($defaultOptions, $customOptions, $options);
  524. $res['d'] = $this->day($field, $customOptions);
  525. $customOptions = array(
  526. 'id' => $modelName.$fieldName.'-mm',
  527. 'class' => 'month'
  528. );
  529. $customOptions = array_merge($defaultOptions, $customOptions, $options);
  530. $res['m'] = $this->month($field, $customOptions);
  531. $customOptions = array(
  532. 'id' => $modelName.$fieldName,
  533. 'class' => 'year'
  534. );
  535. $customOptions = array_merge($defaultOptions, $customOptions, $options);
  536. $minYear = $customOptions['minYear'];
  537. $maxYear = $customOptions['maxYear'];
  538. $res['y'] = $this->year($field, $minYear, $maxYear, $customOptions);
  539. if (isset($options['class'])) {
  540. $class = $options['class'];
  541. unset($options['class']);
  542. }
  543. $select = implode($options['separator'], $res);
  544. if ($this->isFieldError($field)) {
  545. $error = $this->error($field);
  546. } else {
  547. $error = '';
  548. }
  549. if (!empty($callbacks)) {
  550. //callbackFunctions:{"create":...,"dateset":[updateBox]},
  551. $c = $callbacks['update'];
  552. $callbacks = 'callbackFunctions:{"dateset":['.$c.']},';
  553. }
  554. if (!empty($customOptions['type']) && $customOptions['type'] == 'text') {
  555. $script = '
  556. <script type="text/javascript">
  557. // <![CDATA[
  558. var opts = {
  559. formElements:{"'.$modelName.$fieldName.'":"d-dt-m-dt-Y"},
  560. showWeeks:true,
  561. statusFormat:"l-cc-sp-d-sp-F-sp-Y",
  562. '.(!empty($callbacks)?$callbacks:'').'
  563. // Position the button within a wrapper span with an id of "button-wrapper"
  564. positioned:"button-wrapper"
  565. };
  566. datePickerController.createDatePicker(opts);
  567. // ]]>
  568. </script>
  569. ';
  570. $options = array_merge(array('id' => $modelName.$fieldName), $options);
  571. $select = $this->text($field, $options);
  572. return '<div class="input date'.(!empty($error)?' error':'').'">'.$this->label($modelName.'.'.$field, $options['label']).''.$select.''.$error.'</div>'.$script;
  573. }
  574. if ($return) {
  575. return $select;
  576. }
  577. $script = '
  578. <script type="text/javascript">
  579. // <![CDATA[
  580. var opts = {
  581. formElements:{"'.$modelName.$fieldName.'":"Y","'.$modelName.$fieldName.'-mm":"m","'.$modelName.$fieldName.'-dd":"d"},
  582. showWeeks:true,
  583. statusFormat:"l-cc-sp-d-sp-F-sp-Y",
  584. '.(!empty($callbacks)?$callbacks:'').'
  585. // Position the button within a wrapper span with an id of "button-wrapper"
  586. positioned:"button-wrapper"
  587. };
  588. datePickerController.createDatePicker(opts);
  589. // ]]>
  590. </script>
  591. ';
  592. return '<div class="input date'.(!empty($error)?' error':'').'">'.$this->label($modelName.'.'.$field, $options['label']).''.$select.''.$error.'</div>'.$script;
  593. }
  594. /**
  595. * @deprecated
  596. * use Form::dateTimeExt
  597. */
  598. public function dateTime($field, $options = array(), $tf = 24, $a = array()) {
  599. # temp fix
  600. if (!is_array($options)) {
  601. /*
  602. if ($options === null) {
  603. $options = 'DMY';
  604. }
  605. */
  606. return parent::dateTime($field, $options, $tf, $a);
  607. }
  608. return $this->dateTimeExt($field, $options);
  609. }
  610. /**
  611. * @deprecated
  612. * use Form::timeExt
  613. */
  614. public function time($field, $options = array()) {
  615. return $this->timeExt($field, $options);
  616. }
  617. public function timeExt($field, $options = array()) {
  618. $return = false;
  619. if (isset($options['return'])) {
  620. $return = $options['return'];
  621. unset($options['return']);
  622. }
  623. $this->dateScripts(array('time'));
  624. $res = array();
  625. if (!isset($options['separator'])) {
  626. $options['separator'] = ':';
  627. }
  628. if (!isset($options['label'])) {
  629. $options['label'] = null;
  630. }
  631. $defaultOptions = array(
  632. 'empty' => false,
  633. 'timeFormat' => 24,
  634. );
  635. if (strpos($field, '.') !== false) {
  636. list($model, $field) = explode('.', $field, 2);
  637. } else {
  638. $entity = $this->entity();
  639. $model = $this->model();
  640. }
  641. $fieldname = Inflector::camelize($field);
  642. $customOptions = array_merge($defaultOptions, $options);
  643. $format24Hours = $customOptions['timeFormat'] != '24' ? false : true;
  644. if (strpos($field, '.') !== false) {
  645. list($model, $field) = explode('.', $field, 2);
  646. } else {
  647. $entity = $this->entity();
  648. $model = $this->model();
  649. }
  650. $hourOptions = array_merge($customOptions, array('class'=>'hour'));
  651. $res['h'] = $this->hour($field, $format24Hours, $hourOptions);
  652. $minuteOptions = array_merge($customOptions, array('class'=>'minute'));
  653. $res['m'] = $this->minute($field, $minuteOptions);
  654. $select = implode($options['separator'], $res);
  655. if ($this->isFieldError($field)) {
  656. $error = $this->error($field);
  657. } else {
  658. $error = '';
  659. }
  660. if ($return) {
  661. return $select;
  662. }
  663. /*
  664. $script = '
  665. <script type="text/javascript">
  666. // <![CDATA[
  667. $(document).ready(function() {
  668. $(\'#'.$model.$fieldname.'-timepicker\').jtimepicker({
  669. // Configuration goes here
  670. \'secView\': false
  671. });
  672. });
  673. // ]]>
  674. </script>
  675. ';
  676. */
  677. $script = '';
  678. //<div id="'.$model.$fieldname.'-timepicker"></div>
  679. return '<div class="input date'.(!empty($error)?' error':'').'">'.$this->label($model.'.'.$field, $options['label']).''.$select.''.$error.'</div>'.$script;
  680. }
  681. /** maxLength **/
  682. public $maxLengthOptions = array(
  683. 'maxCharacters' => 255,
  684. //'events' => array(),
  685. 'status' => true,
  686. 'statusClass' => 'status',
  687. 'statusText' => 'characters left',
  688. 'slider' => true
  689. );
  690. public function maxLengthScripts() {
  691. if (!$this->scriptsAdded['maxLength']) {
  692. $this->Html->script('jquery/maxlength/jquery.maxlength', array('inline'=>false));
  693. $this->scriptsAdded['maxLength'] = true;
  694. }
  695. }
  696. /**
  697. * maxLength js for textarea input
  698. * final output
  699. * @param array $selectors with specific settings
  700. * @param array $globalOptions
  701. * @return string with JS code
  702. * 2009-07-30 ms
  703. */
  704. public function maxLength($selectors = array(), $options = array()) {
  705. $this->maxLengthScripts();
  706. $js = '';
  707. $this->maxLengthOptions['statusText'] = __($this->maxLengthOptions['statusText']);
  708. $selectors = (array)$selectors;
  709. foreach ($selectors as $selector => $settings) {
  710. if (is_int($selector)) {
  711. $selector = $settings;
  712. $settings = array();
  713. }
  714. $js .= $this->_maxLength($selector, array_merge($this->maxLengthOptions, $settings));
  715. }
  716. if (!empty($options['plain'])) {
  717. return $js;
  718. }
  719. $js = $this->documentReady($js);
  720. return $this->Html->scriptBlock($js);
  721. }
  722. protected function _maxLength($selector, $settings = array()) {
  723. return '
  724. jQuery(\''.$selector.'\').maxlength('.$this->Js->object($settings, array('quoteKeys'=>false)).');
  725. ';
  726. }
  727. public function scripts($type) {
  728. switch ($type) {
  729. case 'charCount':
  730. $this->Html->script('jquery/plugins/charCount', array('inline'=>false));
  731. $this->Html->css('/js/jquery/plugins/charCount', null, array('inline'=>false));
  732. break;
  733. default:
  734. return false;
  735. }
  736. $this->scriptsAdded[$type] = true;
  737. return true;
  738. }
  739. public $charCountOptions = array(
  740. 'allowed' => 255,
  741. );
  742. public function charCount($selectors = array(), $options = array()) {
  743. $this->scripts('charCount');
  744. $js = '';
  745. $selectors = (array)$selectors;
  746. foreach ($selectors as $selector => $settings) {
  747. if (is_int($selector)) {
  748. $selector = $settings;
  749. $settings = array();
  750. }
  751. $settings = array_merge($this->charCountOptions, $options, $settings);
  752. $js .= 'jQuery(\''.$selector.'\').charCount('.$this->Js->object($settings, array('quoteKeys'=>false)).');';
  753. }
  754. $js = $this->documentReady($js);
  755. return $this->Html->scriptBlock($js, array('inline' => isset($options['inline']) ? $options['inline'] : true));
  756. }
  757. public function documentReady($string) {
  758. return 'jQuery(document).ready(function() {
  759. '.$string.'
  760. });';
  761. }
  762. public function autoCompleteScripts() {
  763. if (!$this->scriptsAdded['autoComplete']) {
  764. $this->Html->script('jquery/autocomplete/jquery.autocomplete', false);
  765. $this->Html->css('/js/jquery/autocomplete/jquery.autocomplete', null, array('inline'=>false));
  766. $this->scriptsAdded['autoComplete'] = true;
  767. }
  768. }
  769. /**
  770. * //TODO
  771. * @param jquery: defaults to null = no jquery markup
  772. * - url, data, object (one is necessary), options
  773. * 2010-01-27 ms
  774. */
  775. public function autoComplete($field = null, $options = array(), $jquery = null) {
  776. $this->autoCompleteScripts();
  777. $defaultOptions = array(
  778. 'autocomplete' => 'off'
  779. );
  780. $options = array_merge($defaultOptions, $options);
  781. if (empty($options['id']) && is_array($jquery)) {
  782. $options['id'] = Inflector::camelize(str_replace(".", "_", $field));
  783. }
  784. $res = $this->input($field, $options);
  785. if (is_array($jquery)) {
  786. # custom one
  787. $res .= $this->_autoComplete($options['id'], $jquery);
  788. }
  789. return $res;
  790. }
  791. protected function _autoComplete($id, $jquery = array()) {
  792. if (!empty($jquery['url'])) {
  793. $var = '"'.$this->Html->url($jquery['url']).'"';
  794. } elseif (!empty($jquery['var'])) {
  795. $var = $jquery['object'];
  796. } else {
  797. $var = '['.$jquery['data'].']';
  798. }
  799. $options = '';
  800. if (!empty($jquery['options'])) {
  801. }
  802. $js = 'jQuery("#'.$id.'").autocomplete('.$var.', {
  803. '.$options.'
  804. });
  805. ';
  806. $js = $this->documentReady($js);
  807. return $this->Html->scriptBlock($js);
  808. }
  809. /** checkboxes **/
  810. public function checkboxScripts() {
  811. if (!$this->scriptsAdded['checkbox']) {
  812. $this->Html->script('jquery/checkboxes/jquery.checkboxes', false);
  813. $this->scriptsAdded['checkbox'] = true;
  814. }
  815. }
  816. /**
  817. * returns script + elements "all", "none" etc
  818. * 2010-02-15 ms
  819. */
  820. public function checkboxScript($id) {
  821. $this->checkboxScripts();
  822. $js = 'jQuery("#'.$id.'").autocomplete('.$var.', {
  823. '.$options.'
  824. });
  825. ';
  826. $js = $this->documentReady($js);
  827. return $this->Html->scriptBlock($js);
  828. }
  829. public function checkboxButtons($buttonsOnly = false) {
  830. $res = '<div>';
  831. $res .= __('Selection').': ';
  832. $res .= $this->Html->link(__('All'), 'javascript:void(0)');
  833. $res .= $this->Html->link(__('None'), 'javascript:void(0)');
  834. $res .= $this->Html->link(__('Revert'), 'javascript:void(0)');
  835. $res .= '</div>';
  836. if ($buttonsOnly !== true) {
  837. $res .= $this->checkboxScript();
  838. }
  839. return $res;
  840. }
  841. /**
  842. * displays a single checkbox - called for each
  843. */
  844. public function _checkbox($id, $group = null, $options = array()) {
  845. $defaults = array(
  846. 'class' => 'checkboxToggle'
  847. );
  848. $options = array_merge($defaults, $options);
  849. return $script . parent::checkbox($fieldName, $options);
  850. }
  851. /** other stuff **/
  852. /**
  853. * echo $this->FormExt->buttons($buttons);
  854. * with
  855. * $buttons = array(
  856. * array(
  857. * 'title' => 'Login',
  858. * 'options' => array('type' => 'submit')
  859. * ),
  860. * array(...)
  861. * );
  862. * @param array $buttons
  863. * @return string $buttonSubmitDiv
  864. * 2009-07-26 ms
  865. */
  866. public function buttons($buttons = null) {
  867. $return = '';
  868. if (!empty($buttons) && is_array($buttons)) {
  869. $buttons_content = '';
  870. foreach ($buttons as $button) {
  871. if (empty($button['options'])) { $button['options'] = array(); }
  872. $buttons_content .= $this->button($button['name'], $button['options']);
  873. }
  874. $return = $this->Html->div('submit', $buttons_content);
  875. }
  876. return $return;
  877. }
  878. /** nice buttons **/
  879. protected $buttons = array();
  880. protected $buttonAlign = 'left';
  881. /**
  882. * @param title
  883. * @param options:
  884. * - color (green, blue, red, orange)
  885. * - url
  886. * - align (left/right)
  887. * @param attributes (html)
  888. * 2010-03-15 ms
  889. */
  890. public function addButton($title, $options = array(), $attr = array()) {
  891. $url = !empty($options['url']) ? $options['url'] : 'javascript:void(0)';
  892. $color = !empty($options['color']) ? ' ovalbutton'.ucfirst($options['color']) : '';
  893. if (isset($options['align'])) {
  894. $this->buttonAlign = $options['align'];
  895. }
  896. if ($this->buttonAlign == 'left') {
  897. $align = 'margin-right:5px';
  898. } elseif ($this->buttonAlign == 'right') {
  899. $align = 'margin-left:5px';
  900. }
  901. $class = 'ovalbutton'.$color;
  902. if (!empty($attr['class'])) {
  903. $class .= ' '.$attr['class'];
  904. }
  905. $style = array();
  906. if (!empty($align)) {
  907. $style[] = $align;
  908. }
  909. if (!empty($attr['class'])) {
  910. $style[] = $attr['style'];
  911. }
  912. $style = implode(';', $style);
  913. $attr = array_merge($attr, array('escape'=>false,'class'=>$class, 'style'=>$style));
  914. //$this->buttons[] = '<a class="ovalbutton'.$color.'"'.$href.''.$align.'><span>'.$title.'</span></a>';
  915. if (!isset($attr['escape']) || $attr['escape'] !== true) {
  916. $title = h($title);
  917. }
  918. $this->buttons[] = $this->Html->link('<span>'.$title.'</span>', $url, $attr);
  919. }
  920. /**
  921. * 2010-03-15 ms
  922. */
  923. public function displayButtons($options = array()) {
  924. $res = '<div class="buttonwrapper" style="text-align: '.$this->buttonAlign.'">'.implode('', $this->buttons).'</div>';
  925. $this->buttons = array();
  926. $this->buttonAlign = 'left';
  927. return $res;
  928. }
  929. /*
  930. public $datetimeQuicklinks = '
  931. public function str_pad(input, pad_length, pad_string, pad_type) {
  932. // http://kevin.vanzonneveld.net
  933. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  934. // + namespaced by: Michael White (http://getsprink.com)
  935. // + input by: Marco van Oort
  936. // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  937. // * example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT');
  938. // * returns 1: '-=-=-=-=-=-Kevin van Zonneveld'
  939. // * example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH');
  940. // * returns 2: '------Kevin van Zonneveld-----'
  941. var half = '',
  942. pad_to_go;
  943. var str_pad_repeater = function (s, len) {
  944. var collect = '',
  945. i;
  946. while (collect.length < len) {
  947. collect += s;
  948. }
  949. collect = collect.substr(0, len);
  950. return collect;
  951. };
  952. input += '';
  953. pad_string = pad_string !== undefined ? pad_string : ' ';
  954. if (pad_type != 'STR_PAD_LEFT' && pad_type != 'STR_PAD_RIGHT' && pad_type != 'STR_PAD_BOTH') {
  955. pad_type = 'STR_PAD_RIGHT';
  956. }
  957. if ((pad_to_go = pad_length - input.length) > 0) {
  958. if (pad_type == 'STR_PAD_LEFT') {
  959. input = str_pad_repeater(pad_string, pad_to_go) + input;
  960. } elseif (pad_type == 'STR_PAD_RIGHT') {
  961. input = input + str_pad_repeater(pad_string, pad_to_go);
  962. } elseif (pad_type == 'STR_PAD_BOTH') {
  963. half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2));
  964. input = half + input + half;
  965. input = input.substr(0, pad_length);
  966. }
  967. }
  968. return input;
  969. }
  970. $(document).ready(function() {
  971. $('.date').append(' <span class="setRemove hand">ENTFERNEN</span> <span class="setToday hand">HEUTE</span> <span class="setNow hand">JETZT</span>');
  972. $('.setRemove').click(function() {
  973. var container = $(this).parent('div');
  974. container.children('.day').val("");
  975. container.children('.month').val("");
  976. container.children('.year').val("");
  977. container.children('.hour').val("");
  978. container.children('.minute').val("");
  979. });
  980. $('.setNow').click(function() {
  981. var d = new Date();
  982. var curr_hour = str_pad(d.getHours(), 2, "0", 'STR_PAD_LEFT');
  983. var curr_minute = str_pad(d.getMinutes(), 2, "0", 'STR_PAD_LEFT');
  984. var container = $(this).parent('div');
  985. container.children('.hour').val(curr_hour);
  986. container.children('.minute').val(curr_minute);
  987. });
  988. $('.setToday').click(function() {
  989. var d = new Date();
  990. var curr_date = str_pad(d.getDate(), 2, "0", 'STR_PAD_LEFT');
  991. var curr_month = str_pad(d.getMonth()+1, 2, "0", 'STR_PAD_LEFT');
  992. var curr_year = str_pad(d.getFullYear(), 2, "4", 'STR_PAD_LEFT');
  993. var container = $(this).parent('div');
  994. container.children('.day').val(curr_date);
  995. container.children('.month').val(curr_month);
  996. container.children('.year').val(curr_year);
  997. });
  998. });
  999. ';
  1000. */
  1001. }