Similar contents

Tag: Activating new accounts in Drupal automatically

Activating new accounts in Drupal automatically

Using Hook you can allow new accounts be activated automatically

By

pablito

created on Sunday, January 14, 2024 - 03:27AM - UTC

Content body

Sometimes we want to enable news accounts automatically instead waiting for approval by adm.
Using the hook_auto_insert, you can allow the new accounts to get enabled, this hook is trigger at the insert of new account into the database and basically change the status of Block to Active.
 

Hook method

A simple and procedural way

/**
* Implements hook_user_insert().
*/
function custom_module_user_insert(UserInterface $account) {
  // Auto active the account.
  // Set the user status to "active".
  $account->activate();
  // Save the user entity.
  $account->save();
}

 

OOP method - EventSubscriber

First  I tried the AccountEvents::SET_USER, but I've noticed that this at this point the object account it was created and after a lot of tests I decide to change the approach. 
So I've installed the contrib module: entity_events, this module allow to replacement for hook_entity_[update/insert/delete], it's really good :)

$ composer require 'drupal/entity_events'


Inside your custom module, path: root/src/EventSubscriber.

 
<?php
 
namespace Drupal\custom_module\EventSubscriber;
 
use Drupal\entity_events\Event\EntityEvent;
use Drupal\entity_events\EventSubscriber\EntityEventSubscriber
// or if you prefer EntityEventInsertSubscriber.php both has the same Event onEntityInsert
use Drupal\user\Entity\User;
 
class CustomUserInsert extends EntityEventSubscriber {
 
  public function onEntityInsert(EntityEvent $event) {
 
    // Get the User entity from the EntityEvent.
    $user_entity = $event->getEntity();
    // Deny these changes if $user_entity is not an instance of User.
    if (!($user_entity instanceof User)) {
      return;
    }
 
    // Check if the 'access' and 'login' fields exist.
    if (!$user_entity->hasField('access') || !$user_entity->hasField('login')) {
      return;
    }

    $user_access = $user_entity->get('access')->value;
    $user_login = $user_entity->get('login')->value;

    // That's mean this insert is from user register.
    if ($user_access !== 0 && $user_login !== 0) {
      return;
    }
 
    // If you want to update the status to 1, you can do the following.
    $user_entity->set('status', 1);
    // Save the changes to the User entity.
    $user_entity->save();

  }
}
 


On your root module path, create this file to allow the Drupal to know your new EventSubscriber

services:
  custom_module.user_auto_enable:
    class: Drupal\custom_module\EventSubscriber\CustomUserInsert
    tags:
      - { name: event_subscriber }


In some cases this hook is not enough, in my case, using Drupal 10, I also changed the user settings to visitors can register.
I used hook again, but this time the hook update to run only once, and it basically get the settings from database and add the visitors to allow register. This combination works pretty good.

/**
* Allow the visitors to get auth without admin approval.
*/
function custom_module_update_10001() {
  // Update the configuration value.
  $config = \Drupal::configFactory()->getEditable('user.settings');
  $config->set('register', 'visitor');
  $config->save();
}


I this case you should to update the database using the drush command: drush updb -y

www-data@3d7a062f7e96:/app$ drush updb -y
 --------------- ----------- --------------- ---------------------------------------------------------------- 
  Module          Update ID   Type            Description                                                     
 --------------- ----------- --------------- ---------------------------------------------------------------- 
  custom_module   10001       hook_update_n   10001 - Allow the visitors to get auth without admin approval.  
 --------------- ----------- --------------- ---------------------------------------------------------------- 
 // Do you wish to run the specified pending updates?: yes.                                                        
>  [notice] Update started: custom_module_update_10001
>  [notice] Update completed: custom_module_update_10001
 [success] Finished performing updates.

 


 That's all!

More content for you

Join the conversation

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
keyboard_arrow_up