FormExtHelper.php 35 KB

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