0

Is there an easy way to add a password reset button to the user page in drupal 8? For user management I need the admin to be able to send password recovery link to users AFTER the user account is created. This button should only be visible to admins.

1

You can create a custom module for that:

modules/custom/resetpassmodule/resetpassmodule.info.yml

name: 'resetPassModule'
type: module
description: 'Reset Password link for administrators'
core: 8.x
package: 'Custom'

modules/custom/resetpassmodule/resetpassmodule.module

<?php

/**
 * @file
 * Contains resetpassmodule.module.
 */

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\Component\Utility\Html;

/**
 * Implements hook_help().
 */
function resetpassmodule_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the resetpassmodule module.
    case 'help.page.resetpassmodule':
      $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 resetpassmodule_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' => [
        'resetpassmodule_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 resetpassmodule_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 = 'resetpassmodule';
  $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_set_message($message);
  \Drupal::logger('mail-log')->notice($message);

}


/**
 * Implements hook_mail().
 */
function resetpassmodule_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;
  }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.