FormExtHelper.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  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')+2
  516. );
  517. $fieldName = Inflector::camelize($fieldName);
  518. $customOptions = array(
  519. 'id' => $modelName.$fieldName.'-dd',
  520. 'class' => 'day'
  521. );
  522. $customOptions = array_merge($defaultOptions, $customOptions, $options);
  523. $res['d'] = $this->day($field, $customOptions);
  524. $customOptions = array(
  525. 'id' => $modelName.$fieldName.'-mm',
  526. 'class' => 'month'
  527. );
  528. $customOptions = array_merge($defaultOptions, $customOptions, $options);
  529. $res['m'] = $this->month($field, $customOptions);
  530. $customOptions = array(
  531. 'id' => $modelName.$fieldName,
  532. 'class' => 'year'
  533. );
  534. $customOptions = array_merge($defaultOptions, $customOptions, $options);
  535. $minYear = $customOptions['minYear'];
  536. $maxYear = $customOptions['maxYear'];
  537. $res['y'] = $this->year($field, $minYear, $maxYear, $customOptions);
  538. if (isset($options['class'])) {
  539. $class = $options['class'];
  540. unset($options['class']);
  541. }
  542. $select = implode($options['separator'], $res);
  543. if ($this->isFieldError($field)) {
  544. $error = $this->error($field);
  545. } else {
  546. $error = '';
  547. }
  548. if (!empty($callbacks)) {
  549. //callbackFunctions:{"create":...,"dateset":[updateBox]},
  550. $c = $callbacks['update'];
  551. $callbacks = 'callbackFunctions:{"dateset":['.$c.']},';
  552. }
  553. if (!empty($customOptions['type']) && $customOptions['type'] == 'text') {
  554. $script = '
  555. <script type="text/javascript">
  556. // <![CDATA[
  557. var opts = {
  558. formElements:{"'.$modelName.$fieldName.'":"d-dt-m-dt-Y"},
  559. showWeeks:true,
  560. statusFormat:"l-cc-sp-d-sp-F-sp-Y",
  561. '.(!empty($callbacks)?$callbacks:'').'
  562. // Position the button within a wrapper span with an id of "button-wrapper"
  563. positioned:"button-wrapper"
  564. };
  565. datePickerController.createDatePicker(opts);
  566. // ]]>
  567. </script>
  568. ';
  569. $options = am(array('id' => $modelName.$fieldName), $options);
  570. $select = $this->text($field, $options);
  571. return '<div class="input date'.(!empty($error)?' error':'').'">'.$this->label($modelName.'.'.$field, $options['label']).''.$select.''.$error.'</div>'.$script;
  572. }
  573. if ($return) {
  574. return $select;
  575. }
  576. $script = '
  577. <script type="text/javascript">
  578. // <![CDATA[
  579. var opts = {
  580. formElements:{"'.$modelName.$fieldName.'":"Y","'.$modelName.$fieldName.'-mm":"m","'.$modelName.$fieldName.'-dd":"d"},
  581. showWeeks:true,
  582. statusFormat:"l-cc-sp-d-sp-F-sp-Y",
  583. '.(!empty($callbacks)?$callbacks:'').'
  584. // Position the button within a wrapper span with an id of "button-wrapper"
  585. positioned:"button-wrapper"
  586. };
  587. datePickerController.createDatePicker(opts);
  588. // ]]>
  589. </script>
  590. ';
  591. return '<div class="input date'.(!empty($error)?' error':'').'">'.$this->label($modelName.'.'.$field, $options['label']).''.$select.''.$error.'</div>'.$script;
  592. }
  593. /**
  594. * @deprecated
  595. * use Form::dateTimeExt
  596. */
  597. public function dateTime($field, $options = array(), $tf = 24, $a = array()) {
  598. # temp fix
  599. if (!is_array($options)) {
  600. /*
  601. if ($options === null) {
  602. $options = 'DMY';
  603. }
  604. */
  605. return parent::dateTime($field, $options, $tf, $a);
  606. }
  607. return $this->dateTimeExt($field, $options);
  608. }
  609. /**
  610. * @deprecated
  611. * use Form::timeExt
  612. */
  613. public function time($field, $options = array()) {
  614. return $this->timeExt($field, $options);
  615. }
  616. public function timeExt($field, $options = array()) {
  617. $return = false;
  618. if (isset($options['return'])) {
  619. $return = $options['return'];
  620. unset($options['return']);
  621. }
  622. $this->dateScripts(array('time'));
  623. $res = array();
  624. if (!isset($options['separator'])) {
  625. $options['separator'] = ':';
  626. }
  627. if (!isset($options['label'])) {
  628. $options['label'] = null;
  629. }
  630. $defaultOptions = array(
  631. 'empty' => false,
  632. 'timeFormat' => 24,
  633. );
  634. if (strpos($field, '.') !== false) {
  635. list($model, $field) = explode('.', $field, 2);
  636. } else {
  637. $entity = $this->entity();
  638. $model = $this->model();
  639. }
  640. $fieldname = Inflector::camelize($field);
  641. $customOptions = array_merge($defaultOptions, $options);
  642. $format24Hours = $customOptions['timeFormat'] != '24' ? false : true;
  643. if (strpos($field, '.') !== false) {
  644. list($model, $field) = explode('.', $field, 2);
  645. } else {
  646. $entity = $this->entity();
  647. $model = $this->model();
  648. }
  649. $hourOptions = array_merge($customOptions, array('class'=>'hour'));
  650. $res['h'] = $this->hour($field, $format24Hours, $hourOptions);
  651. $minuteOptions = array_merge($customOptions, array('class'=>'minute'));
  652. $res['m'] = $this->minute($field, $minuteOptions);
  653. $select = implode($options['separator'], $res);
  654. if ($this->isFieldError($field)) {
  655. $error = $this->error($field);
  656. } else {
  657. $error = '';
  658. }
  659. if ($return) {
  660. return $select;
  661. }
  662. /*
  663. $script = '
  664. <script type="text/javascript">
  665. // <![CDATA[
  666. $(document).ready(function() {
  667. $(\'#'.$model.$fieldname.'-timepicker\').jtimepicker({
  668. // Configuration goes here
  669. \'secView\': false
  670. });
  671. });
  672. // ]]>
  673. </script>
  674. ';
  675. */
  676. $script = '';
  677. //<div id="'.$model.$fieldname.'-timepicker"></div>
  678. return '<div class="input date'.(!empty($error)?' error':'').'">'.$this->label($model.'.'.$field, $options['label']).''.$select.''.$error.'</div>'.$script;
  679. }
  680. /** maxLength **/
  681. public $maxLengthOptions = array(
  682. 'maxCharacters' => 255,
  683. //'events' => array(),
  684. 'status' => true,
  685. 'statusClass' => 'status',
  686. 'statusText' => 'characters left',
  687. 'slider' => true
  688. );
  689. public function maxLengthScripts() {
  690. if (!$this->scriptsAdded['maxLength']) {
  691. $this->Html->script('jquery/maxlength/jquery.maxlength', array('inline'=>false));
  692. $this->scriptsAdded['maxLength'] = true;
  693. }
  694. }
  695. /**
  696. * maxLength js for textarea input
  697. * final output
  698. * @param array $selectors with specific settings
  699. * @param array $globalOptions
  700. * @return string with JS code
  701. * 2009-07-30 ms
  702. */
  703. public function maxLength($selectors = array(), $options = array()) {
  704. $this->maxLengthScripts();
  705. $js = '';
  706. $this->maxLengthOptions['statusText'] = __($this->maxLengthOptions['statusText']);
  707. $selectors = (array)$selectors;
  708. foreach ($selectors as $selector => $settings) {
  709. if (is_int($selector)) {
  710. $selector = $settings;
  711. $settings = array();
  712. }
  713. $js .= $this->_maxLength($selector, array_merge($this->maxLengthOptions, $settings));
  714. }
  715. if (!empty($options['plain'])) {
  716. return $js;
  717. }
  718. $js = $this->documentReady($js);
  719. return $this->Html->scriptBlock($js);
  720. }
  721. protected function _maxLength($selector, $settings = array()) {
  722. return '
  723. jQuery(\''.$selector.'\').maxlength('.$this->Js->object($settings, array('quoteKeys'=>false)).');
  724. ';
  725. }
  726. public function scripts($type) {
  727. switch ($type) {
  728. case 'charCount':
  729. $this->Html->script('jquery/plugins/charCount', array('inline'=>false));
  730. $this->Html->css('/js/jquery/plugins/charCount', null, array('inline'=>false));
  731. break;
  732. default:
  733. return false;
  734. }
  735. $this->scriptsAdded[$type] = true;
  736. return true;
  737. }
  738. public $charCountOptions = array(
  739. 'allowed' => 255,
  740. );
  741. public function charCount($selectors = array(), $options = array()) {
  742. $this->scripts('charCount');
  743. $js = '';
  744. $selectors = (array)$selectors;
  745. foreach ($selectors as $selector => $settings) {
  746. if (is_int($selector)) {
  747. $selector = $settings;
  748. $settings = array();
  749. }
  750. $settings = am($this->charCountOptions, $options, $settings);
  751. $js .= 'jQuery(\''.$selector.'\').charCount('.$this->Js->object($settings, array('quoteKeys'=>false)).');';
  752. }
  753. $js = $this->documentReady($js);
  754. return $this->Html->scriptBlock($js, array('inline' => isset($options['inline']) ? $options['inline'] : true));
  755. }
  756. public function documentReady($string) {
  757. return 'jQuery(document).ready(function() {
  758. '.$string.'
  759. });';
  760. }
  761. public function autoCompleteScripts() {
  762. if (!$this->scriptsAdded['autoComplete']) {
  763. $this->Html->script('jquery/autocomplete/jquery.autocomplete', false);
  764. $this->Html->css('/js/jquery/autocomplete/jquery.autocomplete', null, array('inline'=>false));
  765. $this->scriptsAdded['autoComplete'] = true;
  766. }
  767. }
  768. /**
  769. * //TODO
  770. * @param jquery: defaults to null = no jquery markup
  771. * - url, data, object (one is necessary), options
  772. * 2010-01-27 ms
  773. */
  774. public function autoComplete($field = null, $options = array(), $jquery = null) {
  775. $this->autoCompleteScripts();
  776. $defaultOptions = array(
  777. 'autocomplete' => 'off'
  778. );
  779. $options = array_merge($defaultOptions, $options);
  780. if (empty($options['id']) && is_array($jquery)) {
  781. $options['id'] = Inflector::camelize(str_replace(".", "_", $field));
  782. }
  783. $res = $this->input($field, $options);
  784. if (is_array($jquery)) {
  785. # custom one
  786. $res .= $this->_autoComplete($options['id'], $jquery);
  787. }
  788. return $res;
  789. }
  790. protected function _autoComplete($id, $jquery = array()) {
  791. if (!empty($jquery['url'])) {
  792. $var = '"'.$this->Html->url($jquery['url']).'"';
  793. } elseif (!empty($jquery['var'])) {
  794. $var = $jquery['object'];
  795. } else {
  796. $var = '['.$jquery['data'].']';
  797. }
  798. $options = '';
  799. if (!empty($jquery['options'])) {
  800. }
  801. $js = 'jQuery("#'.$id.'").autocomplete('.$var.', {
  802. '.$options.'
  803. });
  804. ';
  805. $js = $this->documentReady($js);
  806. return $this->Html->scriptBlock($js);
  807. }
  808. /** checkboxes **/
  809. public function checkboxScripts() {
  810. if (!$this->scriptsAdded['checkbox']) {
  811. $this->Html->script('jquery/checkboxes/jquery.checkboxes', false);
  812. $this->scriptsAdded['checkbox'] = true;
  813. }
  814. }
  815. /**
  816. * returns script + elements "all", "none" etc
  817. * 2010-02-15 ms
  818. */
  819. public function checkboxScript($id) {
  820. $this->checkboxScripts();
  821. $js = 'jQuery("#'.$id.'").autocomplete('.$var.', {
  822. '.$options.'
  823. });
  824. ';
  825. $js = $this->documentReady($js);
  826. return $this->Html->scriptBlock($js);
  827. }
  828. public function checkboxButtons($buttonsOnly = false) {
  829. $res = '<div>';
  830. $res .= __('Selection').': ';
  831. $res .= $this->Html->link(__('All'), 'javascript:void(0)');
  832. $res .= $this->Html->link(__('None'), 'javascript:void(0)');
  833. $res .= $this->Html->link(__('Revert'), 'javascript:void(0)');
  834. $res .= '</div>';
  835. if ($buttonsOnly !== true) {
  836. $res .= $this->checkboxScript();
  837. }
  838. return $res;
  839. }
  840. /**
  841. * displays a single checkbox - called for each
  842. */
  843. public function _checkbox($id, $group = null, $options = array()) {
  844. $defaults = array(
  845. 'class' => 'checkboxToggle'
  846. );
  847. $options = am($defaults, $options);
  848. return $script . parent::checkbox($fieldName, $options);
  849. }
  850. /** other stuff **/
  851. /**
  852. * echo $this->FormExt->buttons($buttons);
  853. * with
  854. * $buttons = array(
  855. * array(
  856. * 'title' => 'Login',
  857. * 'options' => array('type' => 'submit')
  858. * ),
  859. * array(...)
  860. * );
  861. * @param array $buttons
  862. * @return string $buttonSubmitDiv
  863. * 2009-07-26 ms
  864. */
  865. public function buttons($buttons = null) {
  866. $return = '';
  867. if (!empty($buttons) && is_array($buttons)) {
  868. $buttons_content = '';
  869. foreach ($buttons as $button) {
  870. if (empty($button['options'])) { $button['options'] = array(); }
  871. $buttons_content .= $this->button($button['name'], $button['options']);
  872. }
  873. $return = $this->Html->div('submit', $buttons_content);
  874. }
  875. return $return;
  876. }
  877. /** nice buttons **/
  878. protected $buttons = array();
  879. protected $buttonAlign = 'left';
  880. /**
  881. * @param title
  882. * @param options:
  883. * - color (green, blue, red, orange)
  884. * - url
  885. * - align (left/right)
  886. * @param attributes (html)
  887. * 2010-03-15 ms
  888. */
  889. public function addButton($title, $options = array(), $attr = array()) {
  890. $url = !empty($options['url']) ? $options['url'] : 'javascript:void(0)';
  891. $color = !empty($options['color']) ? ' ovalbutton'.ucfirst($options['color']) : '';
  892. if (isset($options['align'])) {
  893. $this->buttonAlign = $options['align'];
  894. }
  895. if ($this->buttonAlign == 'left') {
  896. $align = 'margin-right:5px';
  897. } elseif ($this->buttonAlign == 'right') {
  898. $align = 'margin-left:5px';
  899. }
  900. $class = 'ovalbutton'.$color;
  901. if (!empty($attr['class'])) {
  902. $class .= ' '.$attr['class'];
  903. }
  904. $style = array();
  905. if (!empty($align)) {
  906. $style[] = $align;
  907. }
  908. if (!empty($attr['class'])) {
  909. $style[] = $attr['style'];
  910. }
  911. $style = implode(';', $style);
  912. $attr = array_merge($attr, array('escape'=>false,'class'=>$class, 'style'=>$style));
  913. //$this->buttons[] = '<a class="ovalbutton'.$color.'"'.$href.''.$align.'><span>'.$title.'</span></a>';
  914. if (!isset($attr['escape']) || $attr['escape'] !== true) {
  915. $title = h($title);
  916. }
  917. $this->buttons[] = $this->Html->link('<span>'.$title.'</span>', $url, $attr);
  918. }
  919. /**
  920. * 2010-03-15 ms
  921. */
  922. public function displayButtons($options = array()) {
  923. $res = '<div class="buttonwrapper" style="text-align: '.$this->buttonAlign.'">'.implode('', $this->buttons).'</div>';
  924. $this->buttons = array();
  925. $this->buttonAlign = 'left';
  926. return $res;
  927. }
  928. /*
  929. public $datetimeQuicklinks = '
  930. public function str_pad(input, pad_length, pad_string, pad_type) {
  931. // http://kevin.vanzonneveld.net
  932. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  933. // + namespaced by: Michael White (http://getsprink.com)
  934. // + input by: Marco van Oort
  935. // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  936. // * example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT');
  937. // * returns 1: '-=-=-=-=-=-Kevin van Zonneveld'
  938. // * example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH');
  939. // * returns 2: '------Kevin van Zonneveld-----'
  940. var half = '',
  941. pad_to_go;
  942. var str_pad_repeater = function (s, len) {
  943. var collect = '',
  944. i;
  945. while (collect.length < len) {
  946. collect += s;
  947. }
  948. collect = collect.substr(0, len);
  949. return collect;
  950. };
  951. input += '';
  952. pad_string = pad_string !== undefined ? pad_string : ' ';
  953. if (pad_type != 'STR_PAD_LEFT' && pad_type != 'STR_PAD_RIGHT' && pad_type != 'STR_PAD_BOTH') {
  954. pad_type = 'STR_PAD_RIGHT';
  955. }
  956. if ((pad_to_go = pad_length - input.length) > 0) {
  957. if (pad_type == 'STR_PAD_LEFT') {
  958. input = str_pad_repeater(pad_string, pad_to_go) + input;
  959. } elseif (pad_type == 'STR_PAD_RIGHT') {
  960. input = input + str_pad_repeater(pad_string, pad_to_go);
  961. } elseif (pad_type == 'STR_PAD_BOTH') {
  962. half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2));
  963. input = half + input + half;
  964. input = input.substr(0, pad_length);
  965. }
  966. }
  967. return input;
  968. }
  969. $(document).ready(function() {
  970. $('.date').append(' <span class="setRemove hand">ENTFERNEN</span> <span class="setToday hand">HEUTE</span> <span class="setNow hand">JETZT</span>');
  971. $('.setRemove').click(function() {
  972. var container = $(this).parent('div');
  973. container.children('.day').val("");
  974. container.children('.month').val("");
  975. container.children('.year').val("");
  976. container.children('.hour').val("");
  977. container.children('.minute').val("");
  978. });
  979. $('.setNow').click(function() {
  980. var d = new Date();
  981. var curr_hour = str_pad(d.getHours(), 2, "0", 'STR_PAD_LEFT');
  982. var curr_minute = str_pad(d.getMinutes(), 2, "0", 'STR_PAD_LEFT');
  983. var container = $(this).parent('div');
  984. container.children('.hour').val(curr_hour);
  985. container.children('.minute').val(curr_minute);
  986. });
  987. $('.setToday').click(function() {
  988. var d = new Date();
  989. var curr_date = str_pad(d.getDate(), 2, "0", 'STR_PAD_LEFT');
  990. var curr_month = str_pad(d.getMonth()+1, 2, "0", 'STR_PAD_LEFT');
  991. var curr_year = str_pad(d.getFullYear(), 2, "4", 'STR_PAD_LEFT');
  992. var container = $(this).parent('div');
  993. container.children('.day').val(curr_date);
  994. container.children('.month').val(curr_month);
  995. container.children('.year').val(curr_year);
  996. });
  997. });
  998. ';
  999. */
  1000. }