Drupal 6: Removing a column from a view for unauthenticated users using hook_views_pre_build()

In this tutorial I’ll show how you can programmatically and dynamically remove a column from your view. In my example, I chose to hide an email column from unauthenticated users, but you could apply this code to do pretty much anything.

To get things started, I defined a content type of “Profile” to contain some user details (using the Content Profile module) and used the Devel module’s generate users and nodes functionality to create some sample data. I then created a view to show the data:

people view

Here is my page view display:

people view 2

Now you can add the hook_views_pre_build() function in your module. Since the $view object is large, I recommend using krumo() (which comes with the Devel module) to browse through the $view object’s properties.

<?php
function MYMODULE_views_pre_build(&$view) {

  // check for your view name (in my example: people)
  if ($view->name=='people') {
    krumo($view);
  }

}
?>

The above code will neatly format the $view object in a hierarchical display. You can click to expand each class property.

krumo

As you can see, the $view object has a lot of data in it. At this point, you’ll need to get acquainted with the structure of the handler object of the view ($view->display[‘default’]->handler) and determine what to modify. To remove the email column for unauthenticated users, you can add the following code:

<?php
function MYMODULE_views_pre_build(&$view) {

  // check for your view name (in my example: people)
  if ($view->name=='people') {

    // check if the user is anon
    if (in_array('anonymous user',$GLOBALS['user']->roles)) {

      // remove view hander properties for email column
      unset(
        $view->display['default']->handler->options['fields']['mail'],
        $view->display['default']->handler->options['style_options']['columns']['mail'],
        $view->display['default']->handler->options['style_options']['info']['mail']
      );

    }

  }

}
?>

When I logout my view no longer shows the email column:

people view 3

Updated: