SpinSpire logo

Display of different Views depending on the logged in User

Have you ever desired to have display of different View filter criteria depending on the user's role? There are two ways of achieving this, I will explain both the ways in this article. 

In following example, I want to show 4 search criteria to a user with administrator role: Event title, Date of Event, Location, Event status.  Further, I want to show two search criteria to all other roles: Event title and Location (shown in below images) . 

Administrator View Anonymous View

To achieve this one can create two different views and set permissions for roles (Go to View edit page -> Page Settings -> access, click on Roles and give permissions depending on the roles). The issue with this approach is that two Views on different urls are created. This is not what we need. 

An alternative approach is to write a few lines of php and get different search criteria in the same view and same url. Check out the following code: 

<?php 
function mymod_permission() {
  return array(
    'use advanced search on events' => array(
      'title' => t('Full access for \'Advanced Search\' in Event List'),
    ),
  );
}
function mymod_views_pre_view(&$view) {
  switch ($view->name) {
    case 'event_list': {
      if(!user_access('use advanced search on events')) {
        $view_filters = $view->display_handler->get_option('filters');
        unset($view_filters['field_date_value']);
        unset($view_filters['field_address_title']);
        $view->display_handler->override_option('filters', $view_filters);
      }
      break;
    }
  }
}

In the above code, hook_views_pre_view is used to alter a view before it is displayed; for more information on this hook visit this page. Switch case statement is used to select the view that needs this implementation, here the machine name of the view is 'event_list'.  Next permissions are checked — if the user role does not has permission “use advance search on events”. This permission is defined in hook_permission. Then, unset $view_filters['field_date_value'], $view_filters['field_event_status'] filter fields. PHP function unset() destroys a variable, so the search filters which are not included in the View can be disabled using this function. 

This is an easy way to create different displays of a view based on permission assigned to user role.

NOTE: 

  • These filter criteria are exposed to the users (check "Expose this filter to visitors, to allow them to change it" to expose the filter criteria).

tags: Knowledge Base views drupal