Need some help with your project? Contact me

Altering the display of a View depending on its results in Drupal 7

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.

Now, there is one caveat: for this particular example to work as you’d expect, the View has to be configured to use Content rather than Fields. But that just makes sense doesn’t it?

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.


Thanks for the simple yet powerful example. It works great.

Great post, thanks!


This is really helpful, thanks. But it does not work when I am using the 'Group by' setting. Any ideas on how to get it work?


In my case i need to alter Global: views result counter field. but actually this field not come from content type. so how to i alter this field using hooks.

It's help me :) ty

Is it possible to use this technique to switch style plugins based on view results?

I'm encountering this error:

Fatal error: Call to a member function render() on a non-object in .../sites/all/modules/views/theme/ on line 49

i want to chnage the view listing display field based on the field condition can u help me to solve this.

Add new comment

You can post comments in Markdown and basic HTML tags.
For code blocks, wrap your code within '~~~'. For example:
$var = 'my variable';