FormExtHelper.php 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  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'] = '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'] = '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 boolean $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 boolean $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. */
  404. public function input($fieldName, $options = array()) {
  405. $this->setEntity($fieldName);
  406. $modelKey = $this->model();
  407. $fieldKey = $this->field();
  408. if (isset($options['datalist'])) {
  409. $options['autocomplete'] = 'off';
  410. if (!isset($options['list'])) {
  411. $options['list'] = ucfirst($fieldKey) . 'List';
  412. }
  413. $datalist = $options['datalist'];
  414. $list = '<datalist id="' . $options['list'] . '">';
  415. //$list .= '<!--[if IE]><div style="display: none"><![endif]-->';
  416. foreach ($datalist as $key => $val) {
  417. if (!isset($options['escape']) || $options['escape'] !== false) {
  418. $key = h($key);
  419. $val = h($val);
  420. }
  421. $list .= '<option label="' . $val . '" value="' . $key . '"></option>';
  422. }
  423. //$list .= '<!--[if IE]></div><![endif]-->';
  424. $list .= '</datalist>';
  425. unset($options['datalist']);
  426. $options['after'] = !empty($options['after']) ? $options['after'] . $list : $list;
  427. }
  428. $res = parent::input($fieldName, $options);
  429. return $res;
  430. }
  431. /**
  432. * FormExtHelper::radio()
  433. * Overwrite to avoid "form-control" to be added.
  434. *
  435. * @param mixed $fieldName
  436. * @param mixed $options
  437. * @param mixed $attributes
  438. * @return void
  439. */
  440. public function radio($fieldName, $options = array(), $attributes = array()) {
  441. $attributes = $this->_initInputField($fieldName, $attributes);
  442. if (!empty($attributes['class']) && $attributes['class'] == array('form-control')) {
  443. $attributes['class'] = false;
  444. }
  445. return parent::radio($fieldName, $options, $attributes);
  446. }
  447. /**
  448. * Overwrite the default method with custom enhancements
  449. *
  450. * @return array options
  451. */
  452. protected function _initInputField($field, $options = array()) {
  453. $normalize = true;
  454. if (isset($options['normalize'])) {
  455. $normalize = $options['normalize'];
  456. unset($options['normalize']);
  457. }
  458. $options = parent::_initInputField($field, $options);
  459. if (!empty($options['value']) && is_string($options['value']) && $normalize) {
  460. $options['value'] = str_replace(array("\t", "\r\n", "\n"), ' ', $options['value']);
  461. }
  462. return $options;
  463. }
  464. /** date(time) **/
  465. //TODO: use http://trentrichardson.com/examples/timepicker/
  466. // or maybe: http://pttimeselect.sourceforge.net/example/index.html (if 24 hour + select dropdowns are supported)
  467. /**
  468. * quicklinks: clear, today, ...
  469. */
  470. public function dateScripts($scripts = array(), $quicklinks = false) {
  471. foreach ($scripts as $script) {
  472. if (!$this->scriptsAdded[$script]) {
  473. switch ($script) {
  474. case 'date':
  475. $lang = Configure::read('Config.language');
  476. if (strlen($lang) !== 2) {
  477. App::uses('L10n', 'I18n');
  478. $Localization = new L10n();
  479. $lang = $Localization->map($lang);
  480. }
  481. if (strlen($lang) !== 2) {
  482. $lang = 'en';
  483. }
  484. if ($this->settings['webroot']) {
  485. $this->Html->script('datepicker/lang/' . $lang, false);
  486. $this->Html->script('datepicker/datepicker', false);
  487. $this->Html->css('common/datepicker', array('inline' => false));
  488. } else {
  489. $this->Common->script(array('Tools.Asset|datepicker/lang/' . $lang, 'Tools.Asset|datepicker/datepicker'), false);
  490. $this->Common->css(array('Tools.Asset|datepicker/datepicker'), array('inline' => false));
  491. }
  492. $this->scriptsAdded['date'] = true;
  493. break;
  494. case 'time':
  495. continue;
  496. if ($this->settings['webroot']) {
  497. } else {
  498. //'Tools.Jquery|ui/core/jquery.ui.core', 'Tools.Jquery|ui/core/jquery.ui.widget', 'Tools.Jquery|ui/widgets/jquery.ui.slider',
  499. $this->Common->script(array('Tools.Jquery|plugins/jquery.timepicker.core', 'Tools.Jquery|plugins/jquery.timepicker'), false);
  500. $this->Common->css(array('Tools.Jquery|ui/core/jquery.ui', 'Tools.Jquery|plugins/jquery.timepicker'), array('inline' => false));
  501. }
  502. break;
  503. default:
  504. break;
  505. }
  506. if ($quicklinks) {
  507. }
  508. }
  509. }
  510. }
  511. /**
  512. * FormExtHelper::dateTimeExt()
  513. *
  514. * @param mixed $field
  515. * @param mixed $options
  516. * @return
  517. */
  518. public function dateTimeExt($field, $options = array()) {
  519. $res = array();
  520. if (!isset($options['separator'])) {
  521. $options['separator'] = null;
  522. }
  523. if (!isset($options['label'])) {
  524. $options['label'] = null;
  525. }
  526. if (strpos($field, '.') !== false) {
  527. list($modelName, $field) = explode('.', $field, 2);
  528. } else {
  529. $entity = $this->entity();
  530. $modelName = $this->model();
  531. }
  532. $defaultOptions = array(
  533. 'empty' => false,
  534. 'return' => true,
  535. );
  536. $customOptions = array_merge($defaultOptions, $options);
  537. $res[] = $this->date($field, $customOptions);
  538. $res[] = $this->time($field, $customOptions);
  539. $select = implode(' &nbsp; ', $res);
  540. //return $this->date($field, $options).$select;
  541. if ($this->isFieldError($field)) {
  542. $error = $this->error($field);
  543. } else {
  544. $error = '';
  545. }
  546. $fieldName = Inflector::camelize($field);
  547. $script = '
  548. var opts = {
  549. formElements: {"' . $modelName . $fieldName . '":"%Y", "' . $modelName . $fieldName . '-mm":"%m", "' . $modelName . $fieldName . '-dd":"%d"},
  550. showWeeks: true,
  551. statusFormat: "%l, %d. %F %Y",
  552. ' . (!empty($callbacks) ? $callbacks : '') . '
  553. positioned: "button-' . $modelName . $fieldName . '"
  554. };
  555. datePickerController.createDatePicker(opts);
  556. ';
  557. if ($this->settings['js'] === 'inline') {
  558. $script = $this->_inlineScript($script);
  559. } else {
  560. $this->Js->buffer($script);
  561. $script = '';
  562. }
  563. return '<div class="input date' . (!empty($error) ? ' error' : '') . '">' . $this->label($modelName . '.' . $field, $options['label']) . '' . $select . '' . $error . '</div>' . $script;
  564. }
  565. protected function _inlineScript($script) {
  566. return '<script type="text/javascript">
  567. // <![CDATA[
  568. ' . $script . '
  569. // ]]>
  570. </script>';
  571. }
  572. /**
  573. * @deprecated
  574. * use Form::dateExt
  575. */
  576. public function date($field, $options = array()) {
  577. return $this->dateExt($field, $options);
  578. }
  579. /**
  580. * Date input (day, month, year) + js
  581. * @see http://www.frequency-decoder.com/2006/10/02/unobtrusive-date-picker-widgit-update/
  582. * @param field (field or Model.field)
  583. * @param options
  584. * - separator (between day, month, year)
  585. * - label
  586. * - empty
  587. * - disableDays (TODO!)
  588. * - minYear/maxYear (TODO!) / rangeLow/rangeHigh (xxxx-xx-xx or today)
  589. */
  590. public function dateExt($field, $options = array()) {
  591. $return = false;
  592. if (isset($options['return'])) {
  593. $return = $options['return'];
  594. unset($options['return']);
  595. }
  596. $quicklinks = false;
  597. if (isset($options['quicklinks'])) {
  598. $quicklinks = $options['quicklinks'];
  599. unset($options['quicklinks']);
  600. }
  601. if (isset($options['callbacks'])) {
  602. $callbacks = $options['callbacks'];
  603. unset($options['callbacks']);
  604. }
  605. $this->dateScripts(array('date'), $quicklinks);
  606. $res = array();
  607. if (!isset($options['separator'])) {
  608. $options['separator'] = '-';
  609. }
  610. if (!isset($options['label'])) {
  611. $options['label'] = null;
  612. }
  613. if (isset($options['disableDays'])) {
  614. $disableDays = $options['disableDays'];
  615. }
  616. if (isset($options['highligtDays'])) {
  617. $highligtDays = $options['highligtDays'];
  618. } else {
  619. $highligtDays = '67';
  620. }
  621. if (strpos($field, '.') !== false) {
  622. list($modelName, $fieldName) = explode('.', $field, 2);
  623. } else {
  624. $entity = $this->entity();
  625. $modelName = $this->model();
  626. $fieldName = $field;
  627. }
  628. if (isset($options['class'])) {
  629. $class = $options['class'];
  630. unset($options['class']);
  631. }
  632. $blacklist = array('timeFormat' => null, 'dateFormat' => null, 'minYear' => null, 'maxYear' => null, 'separator' => null);
  633. $defaultOptions = array(
  634. 'empty' => false,
  635. 'minYear' => date('Y') - 10,
  636. 'maxYear' => date('Y') + 10
  637. );
  638. $defaultOptions = array_merge($defaultOptions, (array)Configure::read('Form.date'));
  639. $fieldName = Inflector::camelize($fieldName);
  640. $customOptions = array(
  641. 'id' => $modelName . $fieldName . '-dd',
  642. 'class' => 'form-control day'
  643. );
  644. $customOptions = array_merge($defaultOptions, $customOptions, $options);
  645. $customOptions = array_diff_key($customOptions, $blacklist);
  646. $res['d'] = $this->day($field, $customOptions);
  647. $customOptions = array(
  648. 'id' => $modelName . $fieldName . '-mm',
  649. 'class' => 'form-control month',
  650. );
  651. $customOptions = array_merge($defaultOptions, $customOptions, $options);
  652. $customOptions = array_diff_key($customOptions, $blacklist);
  653. $res['m'] = $this->month($field, $customOptions);
  654. $customOptions = array(
  655. 'id' => $modelName . $fieldName,
  656. 'class' => 'form-control year'
  657. );
  658. $customOptions = array_merge($defaultOptions, $customOptions, $options);
  659. $minYear = $customOptions['minYear'];
  660. $maxYear = $customOptions['maxYear'];
  661. $customOptions = array_diff_key($customOptions, $blacklist);
  662. $res['y'] = $this->year($field, $minYear, $maxYear, $customOptions);
  663. $select = implode($options['separator'], $res);
  664. if ($this->isFieldError($field)) {
  665. $error = $this->error($field);
  666. } else {
  667. $error = '';
  668. }
  669. if (!empty($callbacks)) {
  670. //callbackFunctions:{"create":...,"dateset":[updateBox]},
  671. $c = $callbacks['update'];
  672. $callbacks = 'callbackFunctions:{"dateset":[' . $c . ']},';
  673. }
  674. if (!empty($customOptions['type']) && $customOptions['type'] === 'text') {
  675. $script = '
  676. var opts = {
  677. formElements: {"' . $modelName . $fieldName . '":"%Y", "' . $modelName . $fieldName . '-mm":"%m", "' . $modelName . $fieldName . '-dd":"%d"},
  678. showWeeks: true,
  679. fillGrid: true,
  680. constrainSelection: true,
  681. statusFormat: "%l, %d. %F %Y",
  682. ' . (!empty($callbacks) ? $callbacks : '') . '
  683. positioned: "button-' . $modelName . $fieldName . '"
  684. };
  685. datePickerController.createDatePicker(opts);
  686. ';
  687. if ($this->settings['js'] === 'inline') {
  688. $script = $this->_inlineScript($script);
  689. } else {
  690. $this->Js->buffer($script);
  691. $script = '';
  692. }
  693. $options = array_merge(array('id' => $modelName . $fieldName), $options);
  694. $select = $this->text($field, $options);
  695. return '<div class="input date' . (!empty($error) ? ' error' : '') . '">' . $this->label($modelName . '.' . $field, $options['label']) . '' . $select . '' . $error . '</div>' . $script;
  696. }
  697. if ($return) {
  698. return $select;
  699. }
  700. $script = '
  701. var opts = {
  702. formElements:{"' . $modelName . $fieldName . '":"%Y", "' . $modelName . $fieldName . '-mm":"%m", "' . $modelName . $fieldName . '-dd":"%d"},
  703. showWeeks:true,
  704. fillGrid:true,
  705. constrainSelection:true,
  706. statusFormat:"%l, %d. %F %Y",
  707. ' . (!empty($callbacks) ? $callbacks : '') . '
  708. // Position the button within a wrapper span with an id of "button-wrapper"
  709. positioned:"button-' . $modelName . $fieldName . '"
  710. };
  711. datePickerController.createDatePicker(opts);
  712. ';
  713. if ($this->settings['js'] === 'inline') {
  714. $script = $this->_inlineScript($script);
  715. } else {
  716. $this->Js->buffer($script);
  717. $script = '';
  718. }
  719. return '<div class="input date' . (!empty($error) ? ' error' : '') . '">' . $this->label($modelName . '.' . $field, $options['label']) . '' . $select . '' . $error . '</div>' . $script;
  720. }
  721. /**
  722. * Custom fix to overwrite the default of non iso 12 hours to 24 hours.
  723. * Try to use Form::dateTimeExt, though.
  724. *
  725. * @see https://cakephp.lighthouseapp.com/projects/42648/tickets/3945-form-helper-should-use-24-hour-format-as-default-iso-8601
  726. *
  727. * @param string $field
  728. * @param mixed $options
  729. * @return string Generated set of select boxes for the date and time formats chosen.
  730. */
  731. public function dateTime($field, $options = array(), $timeFormat = 24, $attributes = array()) {
  732. # temp fix
  733. if (!is_array($options)) {
  734. return parent::dateTime($field, $options, $timeFormat, $attributes);
  735. }
  736. return $this->dateTimeExt($field, $options);
  737. }
  738. /**
  739. * @deprecated
  740. * use Form::timeExt
  741. */
  742. public function time($field, $options = array()) {
  743. return $this->timeExt($field, $options);
  744. }
  745. public function timeExt($field, $options = array()) {
  746. $return = false;
  747. if (isset($options['return'])) {
  748. $return = $options['return'];
  749. unset($options['return']);
  750. }
  751. $this->dateScripts(array('time'));
  752. $res = array();
  753. if (!isset($options['separator'])) {
  754. $options['separator'] = ':';
  755. }
  756. if (!isset($options['label'])) {
  757. $options['label'] = null;
  758. }
  759. $defaultOptions = array(
  760. 'empty' => false,
  761. 'timeFormat' => 24,
  762. );
  763. if (strpos($field, '.') !== false) {
  764. list($model, $field) = explode('.', $field, 2);
  765. } else {
  766. $entity = $this->entity();
  767. $model = $this->model();
  768. }
  769. $fieldname = Inflector::camelize($field);
  770. $customOptions = array_merge($defaultOptions, $options);
  771. $format24Hours = (int)$customOptions['timeFormat'] !== 24 ? false : true;
  772. if (strpos($field, '.') !== false) {
  773. list($model, $field) = explode('.', $field, 2);
  774. } else {
  775. $entity = $this->entity();
  776. $model = $this->model();
  777. }
  778. $blacklist = array('timeFormat' => null, 'dateFormat' => null, 'separator' => null);
  779. $hourOptions = array_merge($customOptions, array('class' => 'form-control hour'));
  780. $hourOptions = array_diff_key($hourOptions, $blacklist);
  781. $res['h'] = $this->hour($field, $format24Hours, $hourOptions);
  782. $minuteOptions = array_merge($customOptions, array('class' => 'form-control minute'));
  783. $minuteOptions = array_diff_key($minuteOptions, $blacklist);
  784. $res['m'] = $this->minute($field, $minuteOptions);
  785. $select = implode($options['separator'], $res);
  786. if ($this->isFieldError($field)) {
  787. $error = $this->error($field);
  788. } else {
  789. $error = '';
  790. }
  791. if ($return) {
  792. return $select;
  793. }
  794. /*
  795. $script = '
  796. <script type="text/javascript">
  797. // <![CDATA[
  798. $(document).ready(function() {
  799. $(\'#'.$model.$fieldname.'-timepicker\').jtimepicker({
  800. // Configuration goes here
  801. \'secView\': false
  802. });
  803. });
  804. // ]]>
  805. </script>
  806. ';
  807. */
  808. $script = '';
  809. //<div id="'.$model.$fieldname.'-timepicker"></div>
  810. return '<div class="input date' . (!empty($error) ? ' error' : '') . '">' . $this->label($model . '.' . $field, $options['label']) . '' . $select . '' . $error . '</div>' . $script;
  811. }
  812. public $maxLengthOptions = array(
  813. 'maxCharacters' => 255,
  814. //'events' => array(),
  815. 'status' => true,
  816. 'statusClass' => 'status',
  817. 'statusText' => 'characters left',
  818. 'slider' => true
  819. );
  820. /**
  821. * FormExtHelper::maxLengthScripts()
  822. *
  823. * @return void
  824. */
  825. public function maxLengthScripts() {
  826. if (!$this->scriptsAdded['maxLength']) {
  827. $this->Html->script('jquery/maxlength/jquery.maxlength', array('inline' => false));
  828. $this->scriptsAdded['maxLength'] = true;
  829. }
  830. }
  831. /**
  832. * MaxLength js for textarea input
  833. * final output
  834. * @param array $selectors with specific settings
  835. * @param array $globalOptions
  836. * @return string with JS code
  837. */
  838. public function maxLength($selectors = array(), $options = array()) {
  839. $this->maxLengthScripts();
  840. $js = '';
  841. $this->maxLengthOptions['statusText'] = __($this->maxLengthOptions['statusText']);
  842. $selectors = (array)$selectors;
  843. foreach ($selectors as $selector => $settings) {
  844. if (is_int($selector)) {
  845. $selector = $settings;
  846. $settings = array();
  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 = array()) {
  857. return '
  858. jQuery(\'' . $selector . '\').maxlength(' . $this->Js->object($settings, array('quoteKeys' => false)) . ');
  859. ';
  860. }
  861. /**
  862. * FormExtHelper::scripts()
  863. *
  864. * @param string $type
  865. * @return boolean Success
  866. */
  867. public function scripts($type) {
  868. switch ($type) {
  869. case 'charCount':
  870. $this->Html->script('jquery/plugins/charCount', array('inline' => false));
  871. $this->Html->css('/js/jquery/plugins/charCount', array('inline' => false));
  872. break;
  873. default:
  874. return false;
  875. }
  876. $this->scriptsAdded[$type] = true;
  877. return true;
  878. }
  879. public $charCountOptions = array(
  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 = array(), $options = array()) {
  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 = array();
  897. }
  898. $settings = array_merge($this->charCountOptions, $options, $settings);
  899. $js .= 'jQuery(\'' . $selector . '\').charCount(' . $this->Js->object($settings, array('quoteKeys' => false)) . ');';
  900. }
  901. $js = $this->documentReady($js);
  902. return $this->Html->scriptBlock($js, array('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. public function autoCompleteScripts() {
  914. if (!$this->scriptsAdded['autoComplete']) {
  915. $this->Html->script('jquery/autocomplete/jquery.autocomplete', false);
  916. $this->Html->css('/js/jquery/autocomplete/jquery.autocomplete', array('inline' => false));
  917. $this->scriptsAdded['autoComplete'] = true;
  918. }
  919. }
  920. /**
  921. * //TODO
  922. * @param jquery: defaults to null = no jquery markup
  923. * - url, data, object (one is necessary), options
  924. */
  925. public function autoComplete($field = null, $options = array(), $jquery = null) {
  926. $this->autoCompleteScripts();
  927. $defaultOptions = array(
  928. 'autocomplete' => 'off'
  929. );
  930. $options = array_merge($defaultOptions, $options);
  931. if (empty($options['id']) && is_array($jquery)) {
  932. $options['id'] = Inflector::camelize(str_replace(".", "_", $field));
  933. }
  934. $res = $this->input($field, $options);
  935. if (is_array($jquery)) {
  936. # custom one
  937. $res .= $this->_autoCompleteJs($options['id'], $jquery);
  938. }
  939. return $res;
  940. }
  941. protected function _autoCompleteJs($id, $jquery = array()) {
  942. if (!empty($jquery['url'])) {
  943. $var = '"' . $this->Html->url($jquery['url']) . '"';
  944. } elseif (!empty($jquery['var'])) {
  945. $var = $jquery['object'];
  946. } else {
  947. $var = '[' . $jquery['data'] . ']';
  948. }
  949. $options = '';
  950. if (!empty($jquery['options'])) {
  951. }
  952. $js = 'jQuery("#' . $id . '").autocomplete(' . $var . ', {
  953. ' . $options . '
  954. });
  955. ';
  956. $js = $this->documentReady($js);
  957. return $this->Html->scriptBlock($js);
  958. }
  959. /** checkboxes **/
  960. public function checkboxScripts() {
  961. if (!$this->scriptsAdded['checkbox']) {
  962. $this->Html->script('jquery/checkboxes/jquery.checkboxes', false);
  963. $this->scriptsAdded['checkbox'] = true;
  964. }
  965. }
  966. /**
  967. * Returns script + elements "all", "none" etc
  968. */
  969. public function checkboxScript($id) {
  970. $this->checkboxScripts();
  971. $js = 'jQuery("#' . $id . '").autocomplete(' . $var . ', {
  972. ' . $options . '
  973. });
  974. ';
  975. $js = $this->documentReady($js);
  976. return $this->Html->scriptBlock($js);
  977. }
  978. public function checkboxButtons($buttonsOnly = false) {
  979. $res = '<div>';
  980. $res .= __('Selection') . ': ';
  981. $res .= $this->Html->link(__('All'), 'javascript:void(0)');
  982. $res .= $this->Html->link(__('None'), 'javascript:void(0)');
  983. $res .= $this->Html->link(__('Revert'), 'javascript:void(0)');
  984. $res .= '</div>';
  985. if ($buttonsOnly !== true) {
  986. $res .= $this->checkboxScript();
  987. }
  988. return $res;
  989. }
  990. /**
  991. * Displays a single checkbox - called for each
  992. */
  993. public function _checkbox($id, $group = null, $options = array()) {
  994. $defaults = array(
  995. 'class' => 'checkboxToggle'
  996. );
  997. $options = array_merge($defaults, $options);
  998. return $script . parent::checkbox($fieldName, $options);
  999. }
  1000. }