You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求Drupal 9自定义表单提交后添加用户并自动登录的代码示例

Drupal 9 自定义注册表单提交后自动登录实现代码示例

1. 自定义表单类实现

在你的自定义模块(比如custom_registration)的src/Form目录下创建CustomRegistrationForm.php文件,代码如下:

<?php

namespace Drupal\custom_registration\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\Entity\User;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * 自定义用户注册表单.
 */
class CustomRegistrationForm extends FormBase {

  /**
   * 当前用户服务.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * 构造函数.
   *
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   当前用户服务.
   */
  public function __construct(AccountInterface $current_user) {
    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('current_user')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'custom_registration_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('用户名'),
      '#required' => TRUE,
      '#maxlength' => 60,
    ];

    $form['mail'] = [
      '#type' => 'email',
      '#title' => $this->t('邮箱'),
      '#required' => TRUE,
    ];

    $form['pass'] = [
      '#type' => 'password_confirm',
      '#title' => $this->t('密码'),
      '#required' => TRUE,
      '#size' => 25,
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('注册'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // 获取表单提交的数据
    $values = $form_state->getValues();

    // 创建新用户实体
    $user = User::create([
      'name' => $values['name'],
      'mail' => $values['mail'],
      'pass' => $values['pass'],
      'status' => 1, // 直接激活用户,若需审核可设为0
      'roles' => ['authenticated'], // 赋予认证用户角色
    ]);
    $user->save();

    // 执行自动登录操作
    user_login_finalize($user);

    // 跳转至用户个人页面或首页
    $form_state->setRedirect('user.page');

    $this->messenger()->addStatus($this->t('注册成功,已自动登录!'));
  }

  /**
   * {@inheritdoc}
   */
  public function getAccess() {
    // 仅允许匿名用户访问该表单
    return $this->currentUser->isAnonymous();
  }

}

2. 注册表单路由

在模块的custom_registration.routing.yml文件中添加路由配置:

custom_registration.form:
  path: '/custom-registration'
  defaults:
    _form: '\Drupal\custom_registration\Form\CustomRegistrationForm'
    _title: '自定义注册'
  requirements:
    _access: 'TRUE'

关键说明

  • 用户创建:通过User::create()创建用户实体,设置必要字段后调用save()完成存储。
  • 自动登录:使用Drupal内置的user_login_finalize()函数,该函数会处理用户会话创建、登录状态设置等核心逻辑。
  • 权限控制:表单的getAccess()方法限制仅匿名用户可访问,避免已登录用户重复注册。
  • 用户激活:示例中直接将用户状态设为1(激活),若需管理员审核机制,可将status设为0,后续通过审核流程激活。

内容的提问来源于stack exchange,提问作者Kalyani Anadhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 11:45:38