Altering Drupal 8+ content view to hide content types for user roles
Task
Today's article is about working with Drupal user roles and the default content view.
The task is to hide content type named ‘Specials’ with machine name specials
from content view for user assigned with any of the following roles ‘content_editor_optional’, ‘cms_admin_optional’, ‘content_admin_optional’
How ?
To achieve this we need to alter the view by adding some logic to check current user role and then remove the relevant content type from the view exposed filter.
Below is the content view, it may look a bit different from vanilla (fresh install) Drupal default content view, but the basics are still the same.
Take note of the Machine name and the field named Content: Content type (exposed)
If you click on the “Content: Content type (exposed)” field you can find the field identifier that will be used later in the code.
We are going to use hook_views_post_build
.
According to the views API
Act on the view immediately after the query is built.
Code
Therefore, we can place this hook in a custom module.
/**
* Implements hook_views_post_build().
*/
function my_custom_module_views_post_build(ViewExecutable $view) {
// Get current user.
$user = \Drupal::currentUser();// If admin user, show all.
if ($user->id() == 1) {
return;
}// Target content view.
if ($view->current_display === 'page_1' && $view->id() === 'content') {$roles = [
'content_editor_optional',
'cms_admin_optional',
'content_admin_optional',
];$currentUserRolesArray = $user->getRoles();// Get filter options of content type.
$typeOptions = $view->exposed_widgets['type']['#options'];// Check if current user has _optional roles
// Display Specials in Content type dropdown only for users with non Optional roles,
// else hide them from the user.
if (count(array_intersect($currentUserRolesArray, $roles)) === 0) {
unset($typeOptions['specials']);
}$view->exposed_widgets['type']['#options'] = $typeOptions;}$view->exposed_widgets['type']['#options'] = $typeOptions;
Resources
Full list of API
https://api.drupal.org/api/drupal/core%21core.api.php/group/hooks/9.0.x