FormExtHelper.php 35 KB

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