0

I have an exposed filter on a date value that has it's granularity set to month, so it shows possible year and month values in the form. If I select just a year, no results are returned, even though I know there are posts that should be retrieved based on the year. If I then specify a month, all posts from that month and year are returned.

I need to be able to return results from the entire year when just year is selected. I'm thinking there might be a way to alter the granularity somehow during the request based on whether or not the month was specified? Any thoughts?

1 Answer 1

1

Working solution thus far:

/**
 * Impliments hook_form_views_exposed_form_alter
 *
 * Used to change exposed date filter to year only, as this is not available in the views UI
 */
function bain_views_form_views_exposed_form_alter(&$form, $form_state)
{
    if( $form['#id'] == 'views-exposed-form-news-items-page')
    {
        // dpm($form_state['input']['date']['value']);
        if (isset($form_state['input']['date']['value'])
            && empty($form_state['input']['date']['value']['month']))
        {
            // Switch date formatter to year only
            $form['date']['value']['#date_format'] = 'Y';
            // Add extra validator to handle filter submit
            $form['#validate'][] = 'bain_views_views_exposed_form_validate';
        }
    }
}

/**
 * Custom validator for exposed date filter
 */
function bain_views_views_exposed_form_validate(&$form, &$form_state)
{
    if ($form['#id'] == 'views-exposed-form-news-items-page')
    {
        $handlers = &$form_state['view']->filter;
        $date_handler = $handlers['field_news_date_value'];
        // dpm($date_handler);
        if (!empty($date_handler->options['exposed'])
            && isset($form['date']['value']['#type'])
            && $form['date']['value']['#type'] == 'date_select'
            && $form['date']['value']['#date_format'] == 'Y')
        {
            $date_handler->options['granularity'] = 'year';
            $date_handler->format = 'Y';
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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