FormExtHelper.php 33 KB

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