2
votes

I have a view on my site which lists a video archive and an exposed filter with a Year/Month granularity. My problem is that the filter only accepts inputs where both the Year and Month values are selected, but I really need to make it possible for users to filter by year without necessarily selecting the month and also to be able to select the year first and then refine the search with filtering by month if they want to.

I am a Drupal beginner, so I don't know much about Drupal's infrastructure. I don't even know where views are stored. If I did, maybe I could alter the code somehow.

1

1 Answers

3
votes

I'm not sure if there is a built-in way to make the month optional or not, but this is a possible work around. You could add two exposed filters, one with Year granularity and one with Year-Month granularity. Then you could use hook_form_FORM_ID_alter to alter the exposed form (be sure to add a conditional to check that it is your view and display id). You could add a validate callback so that when the form is submitted you can set the year in the year_month field if the month was selected.

I haven't tested this, but this is generally how I would approach the form_alter.

<?php
function my_module_form_views_exposed_form_alter(&$form, &$form_state) {
  $view = $form_state['view'];
  if ($view->name == 'my_view' && $view->current_display == 'my_display') {
    // Assuming the year exposed filter is 'year' and year-month exposed filter
    // is 'year_month'.
    $form['year_month']['value']['year']['#access'] = FALSE; // Hides the year
    $form['#validate'][] = 'my_module_my_view_filter_validate';
  }
}

function my_module_my_view_filter_validate($form, &$form_state) {
  $values = isset($form_state['values']) ? $form_state['values'] : array();
  // When the month is set, grab the year from the year exposed filter.
  if (isset($values['year_month']['value']['month'])) {
    // If the year is not set, we have set a user warning.
    if (!isset($values['year']['value']['year'])) {
      drupal_set_message(t('Please select a year.'), 'warning');
    }
    else {
      // Otherwise set the year in the year_month filter to the one from our
      // year filter.
      $year = $values['year']['value']['year'];
      $form_state['values']['year_month']['value']['year'] = $year;
    }
  }
}
?>