How to create a custom Views handler

Submitted by tanc on the 8th of January, 2011 at 4:00pm

Ever wanted to alter the output of a date field in Views beyond what a custom date format can do? I needed to be able to show a node’s created date formatted in two different ways depending on whether the date is today or before today: All nodes in my view with a created date of today should only show the time posted, while nodes older than today should show the full date and time posted.

This is impossible to do with a custom format for dates so altering the rendering function of the date handler for Views was required. The method for doing this is not immediately obvious so I thought I’d blog the method I used here.

In the following examples you need to substitute the name of your custom module for the word ‘example’. So if your module is called ‘mymodule’ you need to change example_views_api to mymodule_views_api.

Ok, so in your custom module you need the following hook_views_api implementation:

This just tells views that we are using the views 2 api and the path to our example.views.inc file which in turn will define our custom handler. Next we need to create example.views.inc in our module directory with the following code in it:

hook_views_data_alter allow us to replace the usual date handler function with our own handler: views_handler_field_example_date. This handler is defined with hook_views_handlers and we tell it in which directory to look for the code. We also tell Views that our custom handler has a parent, the original views_handler_field_date. This is important because we are going to extend the parent in the next bit of code.

Finally create the ‘handlers’ directory in your custom module and create a new file in the handlers directory called views_handler_field_example_date.inc

This new class we are defining extends the views_handler_field_date class. This allows us to add our new option to the select widget and make use of the standard rendering function of the parent class.

In the options_form function we are first loading the existing options with parent::options_form($form, $form_state) and then we’re adding our own option.

In the render function we are first checking to see whether our custom option has been selecting and if not we pass the values through the standard parent render function. If we are using our new custom option then this is where we execute our custom logic to determine how to render the date and finally we return the custom rendered date.

For many other fields rendered by Views you can simply create a custom formatter, either using deciphered’s custom formatters module (easy) or by creating it in the usual way in code with theme functions (advanced). Unfortunately a node’s created date needs the Views handler approach to alter its output. Of course if you just want a simple custom date format use Date API’s custom format as its much easier to do in the GUI.