Bees on a Bike

Integrating time fields in Views exposed filter in Drupal

On our latest project for McGill University’s Community Engagement Day we wanted to find a better way for event times to be entered and searched for by people using the site. We discovered timefield which provides a beautiful API alongside a timepicker widget that is missing from the regular Date field. What was missing was a proper integration into a views exposed filter field in order for the widget to appear. We’ll show you how we did this!

Create your content type & views

Exposed filter config

In Drupal 7, you will need to have a content type that contains your new timefield. Then create a new view with an appropriate output and include the Event Time filter, which should be exposed to visitors.

Modify the exposed filter in views

You will need to create a custom module in order to properly modify the exposed filter. Then you can insert the code below. This attaches the appropriate timefield jsQuery settings along with the actual javascript to the exposed filter. For this example, we used the hour field (as shown above) so the form is explicity looking for that in the code.

See the gist on github.

Besides modifying the settings that you require for the timefield you also need to make sure to set a proper variable in the section (shown below) which can be named pretty much anything you like.

$js_settings = array(‘filter-project-event-time’ => array(

Modify the actual form element

Unfortunately, you cannot simply just modify the exposed filter (in the code above) and things suddenly work. The reason being is that the timefield Javascript searches for the field that you just told it to use your settings with. Tragically, there is no CSS variable that can be attached (that I am aware of) within this call as I spent an hour searching :/

With that being said all is not lost. Simply modify your template.php code in your theme layer and add the following code.

See the gist on github.

You will need to modify the #id to match the appropriate field, but if you created the theme as indicated above chances are it matches directly. If you changed the filter name used for the settings before be sure to modify it in the code above as well since you need to set the proper CSS class name to match.

That’s it! If you clear your cache it should display the popup properly and start to enter the hour/minutes as you can within a content type!

Exit mobile version