Direkt zum Inhalt

Devbits

Kleine Code-Schnipsel aus unserem Alltag mit Drupal, PHP und DevOps: Problem, Lösung, Code.

02.04.2026 | Lothar Ferreira Neumann

Updating user roles using a module update hook

You need to migrate users from one role to another – for example, due to changes in permissions, content access strategy, or a cleanup of legacy roles. Manually updating each user is inefficient, especially on sites with many users.

<?php

use Drupal\user\RoleInterface;

/**
 * Remove the old roles and replace them with the new ones.
 */
function MY_MODULE_update_9041(): void {
  $em = \Drupal::entityTypeManager();
  $user_storage = $em->getStorage('user');

  // Ensure the new role exists. If not, create it first.
  $role_storage = $em->getStorage('user_role');
  if ($role_storage->load('new_role') === NULL) {
    /** @var \Drupal\user\RoleInterface $role */
    $role = $role_storage->create([
      'id' => 'new_role',
      'label' => 'New role',
    ]);
    $role->save();
  }

  $uids = \Drupal::entityQuery('user')
    ->accessCheck(FALSE)
    ->execute();

  if (empty($uids)) {
    return;
  }

  /** @var \Drupal\user\UserInterface[] $users */
  $users = $user_storage->loadMultiple($uids);

  foreach ($users as $user) {
    if ($user->hasRole('old_role')) {
      $user->addRole('new_role');
      $user->removeRole('old_role');
    }

    $user->save();
  }
}

Issue:

You need to migrate users from one role to another – for example, due to changes in permissions, content access strategy, or a cleanup of legacy roles. Manually updating each user is inefficient, especially on sites with many users.

Solution:

This update hook first checks whether the target role (new_role) exists. If it does not, the role is created programmatically.

It then fetches all user IDs using entityQuery with accessCheck(FALSE) to ensure all users are included. The user entities are loaded via user storage, and each user is checked for the presence of the legacy role (old_role). If found, the hook adds new_role, removes old_role, and saves the user entity.

This approach ensures consistency across the user base and allows role migration to be handled safely and repeatably as part of a structured deployment process.

22.01.2026 | Michael Ebert

Set default access permissions for some roles in VAPN module

You installed the Views access per node (VAPN) module and activated it on node bundles from type 'my_bundle'. By default, no one except admin has now access to the nodes anymore. (If you are upgrading VAPN from earlier versions, this happens only to nodes that dont have any rolle assigned).

use Drupal\Core\Form\FormStateInterface;

function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Add default values for vapn module so the editor don't need to check this.
  if (isset($form['vapn']) && $form_state->getFormObject()->getEntity()->isNew()) {
    $form['vapn']['content']['widget']['#default_value'] = ['anonymous', 'authenticated'];
  }
}
use Drupal\node\Entity\Node;

function my_module_deploy_vapn_install() {
  $entity_type_manager = \Drupal::service('entity_type.manager');
  $role_storage = $entity_type_manager->getStorage('user_role');
  $node_storage = $entity_type_manager->getStorage('node');
  $nodes = $node_storage->loadByProperties([
    'type' => 'my_bundle'
  ]);

  $roles = array_values($role_storage->loadMultiple(['anonymous', 'authenticated']));
  foreach ($nodes as $node) {
    // First check if already some roles are set. Only needed if you are upgrading vapn.
    if ($node->vapn->isEmpty()) {
      $node->setSyncing(TRUE)
        ->set('vapn', $roles)
        ->save();
    }
  }
}

Issue:

You installed the Views access per node (VAPN) module and activated it on node bundles from type 'my_bundle'. By default, no one except admin has now access to the nodes anymore. (If you are upgrading VAPN from earlier versions, this happens only to nodes that dont have any rolle assigned).

But you would like the restrictions to be "opt-in". By default everything should be accessible and only certain bits of content shall be restricted.

Prerequisites:

Solution:

  1. Alter forms that are enabled for vapn and set "anonymous" and "authenticated" as the default for new nodes.
  2. Implement a deploy hook that sets these permissions as a default to all exsting nodes - if no roles already assigned - in my case only from type "my_bundle".