FormExtHelper.php 30 KB

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