Fatal error when roles value is NULL in AccountForm::buildEntity()

Created on 22 October 2025, 12 days ago
Updated 27 October 2025, 7 days ago

Problem/Motivation

In Drupal\user\AccountForm::buildEntity(), the roles field is processed using the key() function without first checking whether the value retrieved from $form_state is an array. If the roles field is not present in the current form step (as is common in multistep registration forms), this causes a fatal error:

TypeError: key(): Argument #1 ($array) must be of type array, null given

This makes it impossible to use multistep registration or profile forms when the roles field is conditionally excluded or rendered in later steps.

Steps to reproduce

Install and enable the simple_multistep contributed module.

  • Create a user registration form with multiple steps using simple_multistep.
  • Place the roles field in a later step (not in the first one).
  • Submit the first step of the registration form.
  • You will encounter a fatal error on the form submission due to key(NULL).
  • Proposed resolution

    Modify the logic in AccountForm::buildEntity() to ensure key() is only called when the roles value is a valid array:

    <?php
    $roles = $form_state->getValue('roles');
    if (is_array($roles) && is_string(key($roles))) {
      $form_state->setValue('roles', array_keys(array_filter($roles)));
    }
    ?>

    This prevents a fatal error when the roles field is not present in the form state.

    Remaining tasks

    Confirm the fix works in single-step and multi-step forms.
    Create a test to validate behavior when is not set.
    Review the patch/merge request once created.
    Ensure no regressions in user role assignment functionality.

    User interface changes

    None.

    Introduced terminology

    None.

    API changes

    None. This is an internal fix within a core form method.

    Data model changes

    None.

    Release notes snippet

    Fixed a fatal error in user.module when the roles form value is missing during user registration or profile editing. This improves compatibility with multi-step or conditionally-rendered user forms.

    🐛 Bug report
    Status

    Active

    Version

    11.2 🔥

    Component

    user.module

    Created by

    🇵🇰Pakistan web_ant

    Live updates comments and jobs are added and updated live.
    Sign in to follow issues

    Comments & Activities

    Not all content is available!

    It's likely this issue predates Contrib.social: some issue and comment data are missing.

    No activities found.

    Production build 0.71.5 2024