Skip to main content

Drupal Calendar: Use a Drop Down Menu to Change Calendar Dates

We had a Drupal 7 site setup with a default calendar instance that was displaying content of type 'event'. Due to the limited number of events this site would promote, it was decided to change the navigation from the standard 'Next/Previous' to use drop down menus where the user could choose the month/year they wanted to view.

The original look

Steps to accomplish this

Step 1

First, get your view setup to match the original. Then, add a new filter with the date field you are using in the view, in my case the date field is "field_event_date".

Step 2

Setup the filter like the screenshot below:

Step 3

You'll want to be sure to expose the filter to the user and change the label to something that instructs the user on how to use the calendar.

Step 4 - The code

Once you have the above steps completed, it is time to code! Views gives us numerous hooks to alter the view while it is being built. In this case, we want to alter the argument before the view is built. This way we can manually set the argument, and the query will be built automatically with the date we set from the exposed filter. All the magic happens in the hook_views_pre_view() function within a custom module:

  1. function MYMODULE_views_pre_view(&$view, &$display_id, &$args){
  2.   // Make sure we are on the correct view.
  3.   switch($view->name) {
  4.     case 'events_calendar':
  5.       // If the views exposed filter variables are present.
  6.       if(isset($_GET['field_event_date_value'])) {
  7.         // Let's make sure we can use these variables correctly.
  8.         if(is_numeric($_GET['field_event_date_value']['value']['year']) && is_numeric($_GET['field_event_date_value']['value']['month'])) {
  9.           // Alter the $args variable that was passed into the system and set it to our exposed filter values.
  10.           $args = array(filter_xss($_GET['field_event_date_value']['value']['year']) . '-' . filter_xss($_GET['field_event_date_value']['value']['month']));
  11.         }
  12.       } 
  13.     break;
  14.   }
  15. }

Step 5

The last step is to remove the original pager from the view.

The final product looks like this:


Comments