FormExtHelper.php 31 KB

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