FormExtHelper.php 34 KB

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