Email one time Password Reset link to a user from Admin side- Drupal 9

This changed a little bit from Drupal 7 so here's the code.

The module adds a button to the bottom of the User "Edit" page. :) Click the button and it shoots an email with a reset link to that user. :) 

 

YourModuleName.info.yml File

name: 'YourModuleName'
type: module
description: 'Reset Password link for administrators'
core_version_requirement: ^8 || ^9
package: 'Custom'

 

YourModuleName.moduleFile

<?php

 

/**

 * @file

 * Contains YourModuleName.module.

 */

 

use Drupal\Core\Routing\RouteMatchInterface;

use Drupal\Core\Url;

use Drupal\Component\Utility\Html;

use Drupal\Core\Messenger\MessengerInterface;

 

class YourModuleName{

 

  /**

   * The Messenger service.

   *

   * @var \Drupal\Core\Messenger\MessengerInterface

   */

  protected $messenger;

 

  /**

   *Your ModuleNameService constructor.

   *

   * @param \Drupal\Core\Messenger\MessengerInterface $messenger

   *   The messenger service.

   */

  public function __construct(MessengerInterface $messenger) {

    $this->messenger = $messenger;

  }

 

}

/**

 * Implements hook_help().

 */

Function YourModuleName_help($route_name, RouteMatchInterface $route_match) {

  switch ($route_name) {

    // Main module help for the YourModuleName module.

    case 'help.page.YourModuleName':

      $output = '';

      $output .= '<h3>' . t('About') . '</h3>';

      $output .= '<p>' . t('Reset Password link for administrators') . '</p>';

      return $output;

 

    default:

  }

}

 

/**

 * Alter the user edit form

 *

 * @param $form

 * @param \Drupal\Core\Form\FormStateInterface $form_state

 * @param $form_id

 */

Function YourModuleName_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

 

  //Load the current user roles

  $user = \Drupal::currentUser()->getRoles();

  // Only show the reset link button if the user is administrator.

  if(in_array("administrator", $user)) {

 

    //Add the reset button to the form.

    $form['actions']['sendresetlink'] = [

      '#type' => 'submit',

      '#weight' => 999,

      '#limit_validation_errors' => [],

      '#button_type' => 'danger',

      '#submit' => [

        'YourModuleName_send_reset_link_to_account_form'

      ],

      '#value' => t('Sent reset link to account email'),

    ];

  }

 

}

 

/**

 * Custom submit handler for the password reset button

 *

 * @param $form

 * @param \Drupal\Core\Form\FormStateInterface $form_state

 */

Function YourModuleName_send_reset_link_to_account_form(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {

 

  // Load the user entity of the form.

  $account = $form_state->getFormObject()->getEntity();

 

  // Create a timestamp.

  $timestamp = \Drupal::time()->getRequestTime();

  // Set the redirect location after the user of the one time login.

  $path = '' ;

 

  // Create login link from route (Copy pasted this from the drush package)

  $link = Url::fromRoute(

    'user.reset.login',

    [

      'uid' => $account->id(),

      'timestamp' => $timestamp,

      'hash' => user_pass_rehash($account, $timestamp),

    ],

    [

      'absolute' => true,

      'query' => $path ? ['destination' => $path] : [],

      'language' => \Drupal::languageManager()->getLanguage($account->getPreferredLangcode()),

    ]

  )->toString();

 

  // Genereate mail.

  $mailManager = \Drupal::service('plugin.manager.mail');

  $module = 'YourModuleName';

  $key = 'user_reset_links'; // Replace with Your key

  $to = $account->getEmail();

  $langcode = \Drupal::currentUser()->getPreferredLangcode();

  $send = true;

 

  // Set the message and the subject.

  $params['message'] = $link;

  $params['title'] = "One time login link";

 

  // Send mail and collect the result.

  $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);

  if ($result['result'] != true) {

    $message = t('There was a problem sending your email notification to @email.', array('@email' => $to));

    drupal_set_message($message, 'error');

    \Drupal::logger('mail-log')->error($message);

    return;

  }

 

  $message = t('An email notification has been sent to @email ', array('@email' => $to));

  \Drupal::messenger()->addMessage($message);

  \Drupal::logger('mail-log')->notice($message);

 

}

 

 

/**

 * Implements hook_mail().

 */

Function YourModuleName_mail($key, &$message, $params) {

$options = array(

  'langcode' => $message['langcode'],

);

  switch ($key) {

    case 'user_reset_links':

      $message['from'] = \Drupal::config('system.site')->get('mail');

      $message['subject'] = t('Your mail subject Here: @title', array('@title' => $params['title']), $options);

      $message['body'][] = Html::escape($params['message']);

      break;

  }

}