FormExtHelper.php 34 KB

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