This tutorial will show you how to programatically alter the render of your View depending on its result. For example, how to change the View Mode of a row depending on the number of rows in the View’s result.
In this tutorial we will play around a bit with a Drupal hook that allows us to do this kind of thing: hook_views_pre_render. This hook gets called before the View results have been rendered on the page but after the database query has been made. This lets us tap into the data it gathered from the DB and make alterations to the way they get displayed on the page.
To illustrate the power of this hook I chose a pretty interesting example for which you can actually find uses in reality. What I want to accomplish is change the View Mode from teaser to full if the View gets only one row in its result. Pretty handy no? All you have to do is implement the hook in a custom module and apply a couple of .php conditions in it:
function your_module_name_views_pre_render(&$view) {
if ($view->name == 'your_view_name') {
$result = count($view->result);
if ($result == 1) {
$view->style_plugin->row_plugin->options['view_mode'] = 'full';
}
}
}So, like I said, this hook gets called after the DB query is made. In the example above, it checks to apply what comes next only to your View and if the result of the View contains only one row, it changes the View Mode of that one row to full.
So the lesson here is that you can alter the render of a View depending on any condition you can think to apply using the $view object in the hook. You can also add attachments to the output and even alter the content itself.
Hope this helps.
height="38" width="41" id="EXim" alt="eXTReMe Tracker" />



Comments
Thanks
Thanks for the simple yet powerful example. It works great.
Great post, thanks!
Great post, thanks!
Thanx!
Thanx!
Add new comment