Drupal 8/9 Setting date format in Views Better Exposed Filters (BEF) JQuery.ui date calendar widget

Use case

I’m setting up a View in /admin/ to list Nodes with a Date Created column. To refine the nodes I want two filters that can select nodes within a date range, a date equal or greater than and equal to and less than.

Problem

By default JQuery UI uses the American dateformat. MM/DD/YYYY. This means that if you are using a non US dateformat for everything else eg YYYY/MM/DD your exposed Views filter input field will get an invalid date.

This issue has been floating around for over 6 years!

Solution

Create or add to a custom module which includes some JS as a Library to set the date format, dependent on whether the user is in admin or not.

Create custom module

Assuming you know how to work with custom modules…

JS

prefix_example/js/bef-datepicker.js

(function ($, Drupal, drupalSettings) {

    $('.bef-datepicker').each(function(i, obj) {
        $(obj).datepicker({ dateFormat: 'yy-mm-dd' });        
    });

})(jQuery, Drupal, drupalSettings);

Module

prefix_example/prefix_example.module

/*
 * Implements hook_js_alter().
 */
function prefix_example_js_alter(&$js) {
  $js['settings']['data'][] = array('better_exposed_filters'=> array('bef_dateformat'=>'yy/mm/dd'));
}

/**
* Implements hook_preprocess_page().
*/
function prefix_example_preprocess_page(&$variables) { 
  if (\Drupal::currentUser()->hasPermission('access administration pages')) { 
    $variables['#attached']['library'][] = 'prefix_example/bef-datepicker'; 
  } 
}

Library

prefix_example/prefix_example.libraries.yaml

bef-datepicker:
  version: 1.x
  js:
  js/bef-datepicker.js: {}
  dependencies:
  - core/jquery

Dependencies

prefix_example/prefix_example.info.yaml

dependencies:
  - better_exposed_filters:better_exposed_filters
Was this article helpful?
YesNo