FormExtHelper.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  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. if ($this->settings['webroot']) {
  417. $this->Html->script('datepicker/lang/de', false);
  418. $this->Html->script('datepicker/datepicker', false);
  419. $this->Html->css('common/datepicker', null, array('inline'=>false));
  420. } else {
  421. $this->Common->script(array('Tools.Js|datepicker/lang/de', 'Tools.Js|datepicker/datepicker'), false);
  422. $this->Common->css(array('Tools.Js|datepicker/datepicker'), null, array('inline'=>false));
  423. }
  424. $this->scriptsAdded['date'] = true;
  425. break;
  426. case 'time':
  427. continue;
  428. if ($this->settings['webroot']) {
  429. } else {
  430. //'Tools.Jquery|ui/core/jquery.ui.core', 'Tools.Jquery|ui/core/jquery.ui.widget', 'Tools.Jquery|ui/widgets/jquery.ui.slider',
  431. $this->Common->script(array('Tools.Jquery|plugins/jquery.timepicker.core', 'Tools.Jquery|plugins/jquery.timepicker'), false);
  432. $this->Common->css(array('Tools.Jquery|ui/core/jquery.ui', 'Tools.Jquery|plugins/jquery.timepicker'), null, array('inline'=>false));
  433. }
  434. break;
  435. default:
  436. break;
  437. }
  438. if ($quicklinks) {
  439. }
  440. }
  441. }
  442. }
  443. /**
  444. * FormExtHelper::dateTimeExt()
  445. *
  446. * @param mixed $field
  447. * @param mixed $options
  448. * @return
  449. */
  450. public function dateTimeExt($field, $options = array()) {
  451. $res = array();
  452. if (!isset($options['separator'])) {
  453. $options['separator'] = null;
  454. }
  455. if (!isset($options['label'])) {
  456. $options['label'] = null;
  457. }
  458. if (strpos($field, '.') !== false) {
  459. list($model, $field) = explode('.', $field, 2);
  460. } else {
  461. $entity = $this->entity();
  462. $model = $this->model();
  463. }
  464. $defaultOptions = array(
  465. 'empty' => false,
  466. 'return' => true,
  467. );
  468. $customOptions = array_merge($defaultOptions, $options);
  469. $res[] = $this->date($field, $customOptions);
  470. $res[] = $this->time($field, $customOptions);
  471. $select = implode(' &nbsp; ', $res);
  472. //return $this->date($field, $options).$select;
  473. if ($this->isFieldError($field)) {
  474. $error = $this->error($field);
  475. } else {
  476. $error = '';
  477. }
  478. $fieldname = Inflector::camelize($field);
  479. $script = '
  480. <script type="text/javascript">
  481. // <![CDATA[
  482. var opts = {
  483. formElements:{"'.$model.$fieldname.'":"Y","'.$model.$fieldname.'-mm":"m","'.$model.$fieldname.'-dd":"d"},
  484. showWeeks:true,
  485. statusFormat:"l-cc-sp-d-sp-F-sp-Y",
  486. // Position the button within a wrapper span with an id of "button-wrapper"
  487. positioned:"button-wrapper"
  488. };
  489. datePickerController.createDatePicker(opts);
  490. // ]]>
  491. </script>
  492. ';
  493. return '<div class="input date'.(!empty($error)?' error':'').'">'.$this->label($model.'.'.$field, $options['label']).''.$select.''.$error.'</div>'.$script;
  494. }
  495. /**
  496. * @deprecated
  497. * use Form::dateExt
  498. */
  499. public function date($field, $options = array()) {
  500. return $this->dateExt($field, $options);
  501. }
  502. /**
  503. * date input (day, month, year) + js
  504. * @see http://www.frequency-decoder.com/2006/10/02/unobtrusive-date-picker-widgit-update/
  505. * @param field (field or Model.field)
  506. * @param options
  507. * - separator (between day, month, year)
  508. * - label
  509. * - empty
  510. * - disableDays (TODO!)
  511. * - minYear/maxYear (TODO!) / rangeLow/rangeHigh (xxxx-xx-xx or today)
  512. * 2010-01-20 ms
  513. */
  514. public function dateExt($field, $options = array()) {
  515. $return = false;
  516. if (isset($options['return'])) {
  517. $return = $options['return'];
  518. unset($options['return']);
  519. }
  520. $quicklinks = false;
  521. if (isset($options['quicklinks'])) {
  522. $quicklinks = $options['quicklinks'];
  523. unset($options['quicklinks']);
  524. }
  525. if (isset($options['callbacks'])) {
  526. $callbacks = $options['callbacks'];
  527. unset($options['callbacks']);
  528. }
  529. $this->dateScripts(array('date'), $quicklinks);
  530. $res = array();
  531. if (!isset($options['separator'])) {
  532. $options['separator'] = '-';
  533. }
  534. if (!isset($options['label'])) {
  535. $options['label'] = null;
  536. }
  537. if (isset($options['disableDays'])) {
  538. $disableDays = $options['disableDays'];
  539. }
  540. if (isset($options['highligtDays'])) {
  541. $highligtDays = $options['highligtDays'];
  542. } else {
  543. $highligtDays = '67';
  544. }
  545. if (strpos($field, '.') !== false) {
  546. list($modelName, $fieldName) = explode('.', $field, 2);
  547. } else {
  548. $entity = $this->entity();
  549. $modelName = $this->model();
  550. $fieldName = $field;
  551. }
  552. $defaultOptions = array(
  553. 'empty' => false,
  554. 'minYear' => date('Y') - 10,
  555. 'maxYear' => date('Y') + 10
  556. );
  557. $defaultOptions = array_merge($defaultOptions, (array)Configure::read('Form.date'));
  558. $fieldName = Inflector::camelize($fieldName);
  559. $customOptions = array(
  560. 'id' => $modelName.$fieldName.'-dd',
  561. 'class' => 'day'
  562. );
  563. $customOptions = array_merge($defaultOptions, $customOptions, $options);
  564. $res['d'] = $this->day($field, $customOptions);
  565. $customOptions = array(
  566. 'id' => $modelName.$fieldName.'-mm',
  567. 'class' => 'month'
  568. );
  569. $customOptions = array_merge($defaultOptions, $customOptions, $options);
  570. $res['m'] = $this->month($field, $customOptions);
  571. $customOptions = array(
  572. 'id' => $modelName.$fieldName,
  573. 'class' => 'year'
  574. );
  575. $customOptions = array_merge($defaultOptions, $customOptions, $options);
  576. $minYear = $customOptions['minYear'];
  577. $maxYear = $customOptions['maxYear'];
  578. $res['y'] = $this->year($field, $minYear, $maxYear, $customOptions);
  579. if (isset($options['class'])) {
  580. $class = $options['class'];
  581. unset($options['class']);
  582. }
  583. $select = implode($options['separator'], $res);
  584. if ($this->isFieldError($field)) {
  585. $error = $this->error($field);
  586. } else {
  587. $error = '';
  588. }
  589. if (!empty($callbacks)) {
  590. //callbackFunctions:{"create":...,"dateset":[updateBox]},
  591. $c = $callbacks['update'];
  592. $callbacks = 'callbackFunctions:{"dateset":['.$c.']},';
  593. }
  594. if (!empty($customOptions['type']) && $customOptions['type'] === 'text') {
  595. $script = '
  596. <script type="text/javascript">
  597. // <![CDATA[
  598. var opts = {
  599. formElements:{"'.$modelName.$fieldName.'":"d-dt-m-dt-Y"},
  600. showWeeks:true,
  601. statusFormat:"l-cc-sp-d-sp-F-sp-Y",
  602. '.(!empty($callbacks)?$callbacks:'').'
  603. // Position the button within a wrapper span with an id of "button-wrapper"
  604. positioned:"button-wrapper"
  605. };
  606. datePickerController.createDatePicker(opts);
  607. // ]]>
  608. </script>
  609. ';
  610. $options = array_merge(array('id' => $modelName.$fieldName), $options);
  611. $select = $this->text($field, $options);
  612. return '<div class="input date'.(!empty($error)?' error':'').'">'.$this->label($modelName.'.'.$field, $options['label']).''.$select.''.$error.'</div>'.$script;
  613. }
  614. if ($return) {
  615. return $select;
  616. }
  617. $script = '
  618. <script type="text/javascript">
  619. // <![CDATA[
  620. var opts = {
  621. formElements:{"'.$modelName.$fieldName.'":"Y","'.$modelName.$fieldName.'-mm":"m","'.$modelName.$fieldName.'-dd":"d"},
  622. showWeeks:true,
  623. statusFormat:"l-cc-sp-d-sp-F-sp-Y",
  624. '.(!empty($callbacks)?$callbacks:'').'
  625. // Position the button within a wrapper span with an id of "button-wrapper"
  626. positioned:"button-wrapper"
  627. };
  628. datePickerController.createDatePicker(opts);
  629. // ]]>
  630. </script>
  631. ';
  632. return '<div class="input date'.(!empty($error)?' error':'').'">'.$this->label($modelName.'.'.$field, $options['label']).''.$select.''.$error.'</div>'.$script;
  633. }
  634. /**
  635. * @deprecated
  636. * use Form::dateTimeExt
  637. */
  638. public function dateTime($field, $options = array(), $tf = 24, $a = array()) {
  639. # temp fix
  640. if (!is_array($options)) {
  641. /*
  642. if ($options === null) {
  643. $options = 'DMY';
  644. }
  645. */
  646. return parent::dateTime($field, $options, $tf, $a);
  647. }
  648. return $this->dateTimeExt($field, $options);
  649. }
  650. /**
  651. * @deprecated
  652. * use Form::timeExt
  653. */
  654. public function time($field, $options = array()) {
  655. return $this->timeExt($field, $options);
  656. }
  657. public function timeExt($field, $options = array()) {
  658. $return = false;
  659. if (isset($options['return'])) {
  660. $return = $options['return'];
  661. unset($options['return']);
  662. }
  663. $this->dateScripts(array('time'));
  664. $res = array();
  665. if (!isset($options['separator'])) {
  666. $options['separator'] = ':';
  667. }
  668. if (!isset($options['label'])) {
  669. $options['label'] = null;
  670. }
  671. $defaultOptions = array(
  672. 'empty' => false,
  673. 'timeFormat' => 24,
  674. );
  675. if (strpos($field, '.') !== false) {
  676. list($model, $field) = explode('.', $field, 2);
  677. } else {
  678. $entity = $this->entity();
  679. $model = $this->model();
  680. }
  681. $fieldname = Inflector::camelize($field);
  682. $customOptions = array_merge($defaultOptions, $options);
  683. $format24Hours = $customOptions['timeFormat'] !== '24' ? false : true;
  684. if (strpos($field, '.') !== false) {
  685. list($model, $field) = explode('.', $field, 2);
  686. } else {
  687. $entity = $this->entity();
  688. $model = $this->model();
  689. }
  690. $hourOptions = array_merge($customOptions, array('class'=>'hour'));
  691. $res['h'] = $this->hour($field, $format24Hours, $hourOptions);
  692. $minuteOptions = array_merge($customOptions, array('class'=>'minute'));
  693. $res['m'] = $this->minute($field, $minuteOptions);
  694. $select = implode($options['separator'], $res);
  695. if ($this->isFieldError($field)) {
  696. $error = $this->error($field);
  697. } else {
  698. $error = '';
  699. }
  700. if ($return) {
  701. return $select;
  702. }
  703. /*
  704. $script = '
  705. <script type="text/javascript">
  706. // <![CDATA[
  707. $(document).ready(function() {
  708. $(\'#'.$model.$fieldname.'-timepicker\').jtimepicker({
  709. // Configuration goes here
  710. \'secView\': false
  711. });
  712. });
  713. // ]]>
  714. </script>
  715. ';
  716. */
  717. $script = '';
  718. //<div id="'.$model.$fieldname.'-timepicker"></div>
  719. return '<div class="input date'.(!empty($error)?' error':'').'">'.$this->label($model.'.'.$field, $options['label']).''.$select.''.$error.'</div>'.$script;
  720. }
  721. /** maxLength **/
  722. public $maxLengthOptions = array(
  723. 'maxCharacters' => 255,
  724. //'events' => array(),
  725. 'status' => true,
  726. 'statusClass' => 'status',
  727. 'statusText' => 'characters left',
  728. 'slider' => true
  729. );
  730. public function maxLengthScripts() {
  731. if (!$this->scriptsAdded['maxLength']) {
  732. $this->Html->script('jquery/maxlength/jquery.maxlength', array('inline'=>false));
  733. $this->scriptsAdded['maxLength'] = true;
  734. }
  735. }
  736. /**
  737. * maxLength js for textarea input
  738. * final output
  739. * @param array $selectors with specific settings
  740. * @param array $globalOptions
  741. * @return string with JS code
  742. * 2009-07-30 ms
  743. */
  744. public function maxLength($selectors = array(), $options = array()) {
  745. $this->maxLengthScripts();
  746. $js = '';
  747. $this->maxLengthOptions['statusText'] = __($this->maxLengthOptions['statusText']);
  748. $selectors = (array)$selectors;
  749. foreach ($selectors as $selector => $settings) {
  750. if (is_int($selector)) {
  751. $selector = $settings;
  752. $settings = array();
  753. }
  754. $js .= $this->_maxLengthJs($selector, array_merge($this->maxLengthOptions, $settings));
  755. }
  756. if (!empty($options['plain'])) {
  757. return $js;
  758. }
  759. $js = $this->documentReady($js);
  760. return $this->Html->scriptBlock($js);
  761. }
  762. protected function _maxLengthJs($selector, $settings = array()) {
  763. return '
  764. jQuery(\''.$selector.'\').maxlength('.$this->Js->object($settings, array('quoteKeys'=>false)).');
  765. ';
  766. }
  767. public function scripts($type) {
  768. switch ($type) {
  769. case 'charCount':
  770. $this->Html->script('jquery/plugins/charCount', array('inline'=>false));
  771. $this->Html->css('/js/jquery/plugins/charCount', null, array('inline'=>false));
  772. break;
  773. default:
  774. return false;
  775. }
  776. $this->scriptsAdded[$type] = true;
  777. return true;
  778. }
  779. public $charCountOptions = array(
  780. 'allowed' => 255,
  781. );
  782. public function charCount($selectors = array(), $options = array()) {
  783. $this->scripts('charCount');
  784. $js = '';
  785. $selectors = (array)$selectors;
  786. foreach ($selectors as $selector => $settings) {
  787. if (is_int($selector)) {
  788. $selector = $settings;
  789. $settings = array();
  790. }
  791. $settings = array_merge($this->charCountOptions, $options, $settings);
  792. $js .= 'jQuery(\''.$selector.'\').charCount('.$this->Js->object($settings, array('quoteKeys'=>false)).');';
  793. }
  794. $js = $this->documentReady($js);
  795. return $this->Html->scriptBlock($js, array('inline' => isset($options['inline']) ? $options['inline'] : true));
  796. }
  797. /**
  798. * @param string $string
  799. * @return string Js snippet
  800. */
  801. public function documentReady($string) {
  802. return 'jQuery(document).ready(function() {
  803. '.$string.'
  804. });';
  805. }
  806. public function autoCompleteScripts() {
  807. if (!$this->scriptsAdded['autoComplete']) {
  808. $this->Html->script('jquery/autocomplete/jquery.autocomplete', false);
  809. $this->Html->css('/js/jquery/autocomplete/jquery.autocomplete', null, array('inline'=>false));
  810. $this->scriptsAdded['autoComplete'] = true;
  811. }
  812. }
  813. /**
  814. * //TODO
  815. * @param jquery: defaults to null = no jquery markup
  816. * - url, data, object (one is necessary), options
  817. * 2010-01-27 ms
  818. */
  819. public function autoComplete($field = null, $options = array(), $jquery = null) {
  820. $this->autoCompleteScripts();
  821. $defaultOptions = array(
  822. 'autocomplete' => 'off'
  823. );
  824. $options = array_merge($defaultOptions, $options);
  825. if (empty($options['id']) && is_array($jquery)) {
  826. $options['id'] = Inflector::camelize(str_replace(".", "_", $field));
  827. }
  828. $res = $this->input($field, $options);
  829. if (is_array($jquery)) {
  830. # custom one
  831. $res .= $this->_autoCompleteJs($options['id'], $jquery);
  832. }
  833. return $res;
  834. }
  835. protected function _autoCompleteJs($id, $jquery = array()) {
  836. if (!empty($jquery['url'])) {
  837. $var = '"'.$this->Html->url($jquery['url']).'"';
  838. } elseif (!empty($jquery['var'])) {
  839. $var = $jquery['object'];
  840. } else {
  841. $var = '['.$jquery['data'].']';
  842. }
  843. $options = '';
  844. if (!empty($jquery['options'])) {
  845. }
  846. $js = 'jQuery("#'.$id.'").autocomplete('.$var.', {
  847. '.$options.'
  848. });
  849. ';
  850. $js = $this->documentReady($js);
  851. return $this->Html->scriptBlock($js);
  852. }
  853. /**
  854. * Overwrite FormHelper::create() to allow disabling browser html5 validation via configs
  855. *
  856. * @param string $model
  857. * @param array $options
  858. * @return string
  859. */
  860. public function create($model = null, $options = array()) {
  861. if (Configure::read('Validation.browserAutoRequire') === false && !isset($options['novalidate'])) {
  862. $options['novalidate'] = true;
  863. }
  864. return parent::create($model, $options);
  865. }
  866. /** checkboxes **/
  867. public function checkboxScripts() {
  868. if (!$this->scriptsAdded['checkbox']) {
  869. $this->Html->script('jquery/checkboxes/jquery.checkboxes', false);
  870. $this->scriptsAdded['checkbox'] = true;
  871. }
  872. }
  873. /**
  874. * returns script + elements "all", "none" etc
  875. * 2010-02-15 ms
  876. */
  877. public function checkboxScript($id) {
  878. $this->checkboxScripts();
  879. $js = 'jQuery("#'.$id.'").autocomplete('.$var.', {
  880. '.$options.'
  881. });
  882. ';
  883. $js = $this->documentReady($js);
  884. return $this->Html->scriptBlock($js);
  885. }
  886. public function checkboxButtons($buttonsOnly = false) {
  887. $res = '<div>';
  888. $res .= __('Selection').': ';
  889. $res .= $this->Html->link(__('All'), 'javascript:void(0)');
  890. $res .= $this->Html->link(__('None'), 'javascript:void(0)');
  891. $res .= $this->Html->link(__('Revert'), 'javascript:void(0)');
  892. $res .= '</div>';
  893. if ($buttonsOnly !== true) {
  894. $res .= $this->checkboxScript();
  895. }
  896. return $res;
  897. }
  898. /**
  899. * displays a single checkbox - called for each
  900. */
  901. public function _checkbox($id, $group = null, $options = array()) {
  902. $defaults = array(
  903. 'class' => 'checkboxToggle'
  904. );
  905. $options = array_merge($defaults, $options);
  906. return $script . parent::checkbox($fieldName, $options);
  907. }
  908. /** other stuff **/
  909. /**
  910. * echo $this->FormExt->buttons($buttons);
  911. * with
  912. * $buttons = array(
  913. * array(
  914. * 'title' => 'Login',
  915. * 'options' => array('type' => 'submit')
  916. * ),
  917. * array(...)
  918. * );
  919. * @param array $buttons
  920. * @return string $buttonSubmitDiv
  921. * 2009-07-26 ms
  922. */
  923. public function buttons($buttons = null) {
  924. $return = '';
  925. if (!empty($buttons) && is_array($buttons)) {
  926. $buttons_content = '';
  927. foreach ($buttons as $button) {
  928. if (empty($button['options'])) { $button['options'] = array(); }
  929. $buttons_content .= $this->button($button['name'], $button['options']);
  930. }
  931. $return = $this->Html->div('submit', $buttons_content);
  932. }
  933. return $return;
  934. }
  935. /** nice buttons **/
  936. protected $buttons = array();
  937. protected $buttonAlign = 'left';
  938. /**
  939. * @param title
  940. * @param options:
  941. * - color (green, blue, red, orange)
  942. * - url
  943. * - align (left/right)
  944. * @param attributes (html)
  945. * 2010-03-15 ms
  946. */
  947. public function addButton($title, $options = array(), $attr = array()) {
  948. $url = !empty($options['url']) ? $options['url'] : 'javascript:void(0)';
  949. $color = !empty($options['color']) ? ' ovalbutton'.ucfirst($options['color']) : '';
  950. if (isset($options['align'])) {
  951. $this->buttonAlign = $options['align'];
  952. }
  953. if ($this->buttonAlign === 'left') {
  954. $align = 'margin-right:5px';
  955. } elseif ($this->buttonAlign === 'right') {
  956. $align = 'margin-left:5px';
  957. }
  958. $class = 'ovalbutton'.$color;
  959. if (!empty($attr['class'])) {
  960. $class .= ' '.$attr['class'];
  961. }
  962. $style = array();
  963. if (!empty($align)) {
  964. $style[] = $align;
  965. }
  966. if (!empty($attr['class'])) {
  967. $style[] = $attr['style'];
  968. }
  969. $style = implode(';', $style);
  970. $attr = array_merge($attr, array('escape'=>false,'class'=>$class, 'style'=>$style));
  971. //$this->buttons[] = '<a class="ovalbutton'.$color.'"'.$href.''.$align.'><span>'.$title.'</span></a>';
  972. if (!isset($attr['escape']) || $attr['escape'] !== true) {
  973. $title = h($title);
  974. }
  975. $this->buttons[] = $this->Html->link('<span>'.$title.'</span>', $url, $attr);
  976. }
  977. /**
  978. * 2010-03-15 ms
  979. */
  980. public function displayButtons($options = array()) {
  981. $res = '<div class="buttonwrapper" style="text-align: '.$this->buttonAlign.'">'.implode('', $this->buttons).'</div>';
  982. $this->buttons = array();
  983. $this->buttonAlign = 'left';
  984. return $res;
  985. }
  986. /*
  987. public $datetimeQuicklinks = '
  988. public function str_pad(input, pad_length, pad_string, pad_type) {
  989. // http://kevin.vanzonneveld.net
  990. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  991. // + namespaced by: Michael White (http://getsprink.com)
  992. // + input by: Marco van Oort
  993. // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  994. // * example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT');
  995. // * returns 1: '-=-=-=-=-=-Kevin van Zonneveld'
  996. // * example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH');
  997. // * returns 2: '------Kevin van Zonneveld-----'
  998. var half = '',
  999. pad_to_go;
  1000. var str_pad_repeater = function (s, len) {
  1001. var collect = '',
  1002. i;
  1003. while (collect.length < len) {
  1004. collect += s;
  1005. }
  1006. collect = collect.substr(0, len);
  1007. return collect;
  1008. };
  1009. input += '';
  1010. pad_string = pad_string !== undefined ? pad_string : ' ';
  1011. if (pad_type !== 'STR_PAD_LEFT' && pad_type !== 'STR_PAD_RIGHT' && pad_type !== 'STR_PAD_BOTH') {
  1012. pad_type = 'STR_PAD_RIGHT';
  1013. }
  1014. if ((pad_to_go = pad_length - input.length) > 0) {
  1015. if (pad_type === 'STR_PAD_LEFT') {
  1016. input = str_pad_repeater(pad_string, pad_to_go) + input;
  1017. } elseif (pad_type === 'STR_PAD_RIGHT') {
  1018. input = input + str_pad_repeater(pad_string, pad_to_go);
  1019. } elseif (pad_type === 'STR_PAD_BOTH') {
  1020. half = str_pad_repeater(pad_string, Math.ceil(pad_to_go / 2));
  1021. input = half + input + half;
  1022. input = input.substr(0, pad_length);
  1023. }
  1024. }
  1025. return input;
  1026. }
  1027. $(document).ready(function() {
  1028. $('.date').append(' <span class="setRemove hand">ENTFERNEN</span> <span class="setToday hand">HEUTE</span> <span class="setNow hand">JETZT</span>');
  1029. $('.setRemove').click(function() {
  1030. var container = $(this).parent('div');
  1031. container.children('.day').val("");
  1032. container.children('.month').val("");
  1033. container.children('.year').val("");
  1034. container.children('.hour').val("");
  1035. container.children('.minute').val("");
  1036. });
  1037. $('.setNow').click(function() {
  1038. var d = new Date();
  1039. var curr_hour = str_pad(d.getHours(), 2, "0", 'STR_PAD_LEFT');
  1040. var curr_minute = str_pad(d.getMinutes(), 2, "0", 'STR_PAD_LEFT');
  1041. var container = $(this).parent('div');
  1042. container.children('.hour').val(curr_hour);
  1043. container.children('.minute').val(curr_minute);
  1044. });
  1045. $('.setToday').click(function() {
  1046. var d = new Date();
  1047. var curr_date = str_pad(d.getDate(), 2, "0", 'STR_PAD_LEFT');
  1048. var curr_month = str_pad(d.getMonth()+1, 2, "0", 'STR_PAD_LEFT');
  1049. var curr_year = str_pad(d.getFullYear(), 2, "4", 'STR_PAD_LEFT');
  1050. var container = $(this).parent('div');
  1051. container.children('.day').val(curr_date);
  1052. container.children('.month').val(curr_month);
  1053. container.children('.year').val(curr_year);
  1054. });
  1055. });
  1056. ';
  1057. */
  1058. }