Jojodae Ganesh Sivaji
January 19, 2012
Amending the view output is no longer a tedious task. Especially by taking the advantage of settings available in Views 3.x like exclude from the display, style settings, rewrite results, and their sub-settings. The change can be anything simple from adding a <span> wrapper for CSS styling to complex token replacement (thanks to the token module for making the Views module more awesome).
[[{"type":"media","view_mode":"media_original","fid":"82","attributes":{"alt":"","class":"media-image","typeof":"foaf:Image"}}]]
Well, this works great most of the time, however, there are cases where you need a few lines of PHP code to make the output closer to the project's requirements. I hit upon such a case in my recent project. My requirement was to show the time difference from the expiry date (unixtimestamp) field. Something similar to what format_interval() API would return but in a different way.
The quickest and most tempting solution would be to enable Drupal core's PHP filter module and add a code snippet from the Views admin interface. At first look, this might look simple and hassle-free as you don't need to write any module but seriously this is not a Drupal way of doing it. To learn in-depth about why you should avoid PHP filters see https://drupal.stackexchange.com/questions/2509/what-are-the-downsides-of-using-custom-php-code-in-blocks-nodes-views-args
I Googled for views API documentation and came across hook_views_pre_render(). After a few attempts of failure, I figured out the way it works. I have a product node that has an expiry field. In the view output, I need to show the remaining time in terms of the number of days, hours, minutes, and seconds left before expiry.
A quick module that implements hook_views_pre_render() did the trick. All it requires is a few lines of code as below,
Ideally the code above loops through the result items of view and overrides the field_deal_expire value with a value returned by a custom function _kf_products_get_remaining_time().
The function _kf_products_get_remaining_time() returns a string value and it resembles as below,
Besides page and block display, this trick works for additional displays like CSV and XLS file export featured by other modules like Views data export.
Just like how your fellow techies do.
We'd love to talk about how we can work together
Take control of your AWS cloud costs that enables you to grow!