On module install set new content view permissions default values

Created on 10 April 2024, 7 months ago

Problem/Motivation

When the module is enabled on an existing website with a lot of content types, a lot of changes must be done in the module permissions to keep the site running as it was before (user can access content).

I recently had to add a new section with a restricted content to a new role on an existing website with a lot of content types (+15). I use the `node_view_permissions` module which is perfect for this. But when the module is activated, even if the new part is not yet done, I had to change quickly the permissions to allow normal or anonymous users to be able to browse the site.

I think it would be better if the module installation does not change the current behaviour of the existing site.

Proposed resolution

Automatically add the new `view any [bundle] content` permission for all existing node types, to anonymous and connected users roles in `hook_install`.

Here is the proposed code, inspired from the other hooks of the module:


/**
 * @file
 * Contains install and update functions for node_view_permissions.
 */

use Drupal\node\Entity\NodeType;
use Drupal\user\Entity\Role;

/**
 * Implements hook_install().
 */
function node_view_permissions_install() {
  node_access_needs_rebuild(TRUE);

  // Add 'view any [node_type] content' permission
  // for anonymous and connected users.
  $roles = [
    Role::ANONYMOUS_ID,
    Role::AUTHENTICATED_ID,
  ];

  foreach ($roles as $role) {
    $role_object = Role::load($role);
    foreach (NodeType::loadMultiple() as $type) {
      $type_id = $type->id();
      $role_object->grantPermission("view any $type_id content");
    }
    $role_object->save();
  }
}

Feature request
Status

Active

Version

1.0

Component

Code

Created by

🇫🇷France ccrosaz

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Production build 0.71.5 2024