1

I have a view displaying a collection of events with a date field the user can set the range of. For a default value, I have +0 days to +90 days, so the user can see all events during the next 90 days. The image below shows all my setting information for the date filter.

Date exposed filter configuration

Currently, the user sees relative dates when they load the page, as the next image shows: enter image description here

But I would like this to show dates to the user, instead of these relative values when they load the page. In the picture above, if the date they were viewing the page was 1/11/17, I would like the user to see 1/11/17 to 4/11/17 instead of +0 days to +90 days. What would be the simplest way to make this conversion in Drupal 8?

0

Edited - You can apply datepicker to the field, as Jquery Ui date picker is available in Drupal8. For reference see to this

Or,

you can programmatically alter the view query in hook_views_query_alter()

function module_name_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
 // Query alter to provide dynamic date ranges.
 if ($view->id() == 'VIEW ID' && $view->current_display == 'page_1')
 {
    foreach ($query->where[0]['conditions'] as $key) {
      if (array_key_exists(':node__field_start_date_time.field_start_date_time_value[]', $key['value'])) {
        // do anything you want...
        ...
        ...
      }
    }
 }
  • Thank you for the suggestions. I have already installed the Better Exposed Filter module to give my date fields pickers. This is perfect for users to select a date range, as it overwrites the relative date once they make a selection. But when they load the page initially, they still see the relative date. I will give your code a try soon and let you know if I get it to work. – Eric Gilson Jan 13 '17 at 2:53
0

I eventually did something like Ashish's answer but used the hook_form_FORM_ID_alter hook instead of a view hook.

function hook_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (array_key_exists('field_event_start_date_time_value', $form)) {
    $form['field_event_start_date_time_value']['min']['#default_value'] = date('m/d/Y');
    $end_date = new DateTime('+90 days');
    $form['field_event_start_date_time_value']['max']['#default_value'] = date_format($end_date, 'm/d/Y');
   }
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.