FormExtHelper.php 33 KB

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