Do you want to know how to Drupal?

Let's Drupal

User



How to detect the very first login of the user in Drupal 9?

For this we need implement user_login hook and then we check the last access field.

use Drupal\user\Entity\User;

/**
 * Implements hook_user_login().
 */
function mymodule_user_login(User $user) {
  if (empty($user->getLastAccessedTime())) {
    // Do something here.
  }
}

 


How to redirect a user after login in Drupal 9?

Let's imagine we want to send a user to custom route after login in our example to user edit form. How do we do it ?

We need to implement user_login hook

use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\user\Entity\User;

/**
 * Implements hook_user_login().
 */
function mymodule_user_login(User $user) {
    $url = Url::fromRoute('entity.user.edit_form', [
       'user' => $user->id(),
    ]);
    $redirect = new RedirectResponse($url->toString());
    $redirect->send();
}


 


How to add / remove user role programmatically in Drupal 8 ?



User access system based on roles and in some cases we want to assign role based on specific business requirements. 

For this we need to load a user first:

<?php
use Drupal\user\Entity\User;

// pass the correct user id here.
User:load(4); 

or we can load current user

<?php
use Drupal\user\Entity\User;

User::load(\Drupal::currentUser()->id());

Then we add a user role 

// pass machine name of the user.
$user->addRole('administrator');
$user->save();

To remove the role we can use this code

// pass machine name of the user.
$user->removeRole('administrator');
$user->save();