function AccountForm::buildEntity

Same name in other branches
  1. 9 core/modules/user/src/AccountForm.php \Drupal\user\AccountForm::buildEntity()
  2. 8.9.x core/modules/user/src/AccountForm.php \Drupal\user\AccountForm::buildEntity()
  3. 10 core/modules/user/src/AccountForm.php \Drupal\user\AccountForm::buildEntity()

Overrides ContentEntityForm::buildEntity

File

core/modules/user/src/AccountForm.php, line 359

Class

AccountForm
Form controller for the user account forms.

Namespace

Drupal\user

Code

public function buildEntity(array $form, FormStateInterface $form_state) {
    // Change the roles array to a list of enabled roles.
    // @todo Alter the form state as the form values are directly extracted and
    //   set on the field, which throws an exception as the list requires
    //   numeric keys. Allow to override this per field. As this function is
    //   called twice, we have to prevent it from getting the array keys twice.
    if (is_string(key($form_state->getValue('roles')))) {
        $form_state->setValue('roles', array_keys(array_filter($form_state->getValue('roles'))));
    }
    
    /** @var \Drupal\user\UserInterface $account */
    $account = parent::buildEntity($form, $form_state);
    // Translate the empty value '' of language selects to an unset field.
    foreach ([
        'preferred_langcode',
        'preferred_admin_langcode',
    ] as $field_name) {
        if ($form_state->getValue($field_name) === '') {
            $account->{$field_name} = NULL;
        }
    }
    // Set existing password if set in the form state.
    $current_pass = trim($form_state->getValue('current_pass', ''));
    if (strlen($current_pass) > 0) {
        $account->setExistingPassword($current_pass);
    }
    // Skip the protected user field constraint if the user came from the
    // password recovery page.
    $account->_skipProtectedUserFieldConstraint = $form_state->get('user_pass_reset');
    return $account;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.