Display of Different Views Depending on Logged in User
How to show different Drupal view filter criteria based on user roles using hook_views_pre_view.
Have you ever desired to have display of different View filter criteria depending on theuser’srole?There are two ways of achieving this, I will explain both the ways in thisarticle.
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 wantto show two search criteria to all other roles: Event title and Location (shown in below images) .

To achieve thisonecan create two different viewsand set permissions for roles (Goto View edit page ->Page Settings ->access, click on Roles and give permissions depending on the roles).The issue with this approach isthattwo Views on differenturlsare 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 thispage.Switch case statement is used to select the view that needsthis implementation, here the machine name of the view is ‘event_list’.Nextpermissionsare 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).