FormExtHelper.php 30 KB

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