FormExtHelper.php 34 KB

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