FormExtHelper.php 34 KB

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