Chris@0: languageManager = $language_manager; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public static function create(ContainerInterface $container) { Chris@0: return new static( Chris@17: $container->get('entity.repository'), Chris@0: $container->get('language_manager'), Chris@0: $container->get('entity_type.bundle.info'), Chris@0: $container->get('datetime.time') Chris@0: ); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function form(array $form, FormStateInterface $form_state) { Chris@0: /** @var \Drupal\user\UserInterface $account */ Chris@0: $account = $this->entity; Chris@0: $user = $this->currentUser(); Chris@0: $config = \Drupal::config('user.settings'); Chris@0: $form['#cache']['tags'] = $config->getCacheTags(); Chris@0: Chris@0: $language_interface = \Drupal::languageManager()->getCurrentLanguage(); Chris@18: Chris@18: // Check for new account. Chris@0: $register = $account->isAnonymous(); Chris@18: Chris@18: // For a new account, there are 2 sub-cases: Chris@18: // $self_register: A user creates their own, new, account Chris@18: // (path '/user/register') Chris@18: // $admin_create: An administrator creates a new account for another user Chris@18: // (path '/admin/people/create') Chris@18: // If the current user is logged in and has permission to create users Chris@18: // then it must be the second case. Chris@18: $admin_create = $register && $account->access('create'); Chris@18: $self_register = $register && !$admin_create; Chris@0: Chris@0: // Account information. Chris@0: $form['account'] = [ Chris@0: '#type' => 'container', Chris@0: '#weight' => -10, Chris@0: ]; Chris@0: Chris@0: // The mail field is NOT required if account originally had no mail set Chris@0: // and the user performing the edit has 'administer users' permission. Chris@0: // This allows users without email address to be edited and deleted. Chris@0: // Also see \Drupal\user\Plugin\Validation\Constraint\UserMailRequired. Chris@0: $form['account']['mail'] = [ Chris@0: '#type' => 'email', Chris@0: '#title' => $this->t('Email address'), Chris@0: '#description' => $this->t('A valid email address. All emails from the system will be sent to this address. The email address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by email.'), Chris@18: '#required' => !(!$account->getEmail() && $user->hasPermission('administer users')), Chris@0: '#default_value' => (!$register ? $account->getEmail() : ''), Chris@0: ]; Chris@0: Chris@0: // Only show name field on registration form or user can change own username. Chris@0: $form['account']['name'] = [ Chris@0: '#type' => 'textfield', Chris@0: '#title' => $this->t('Username'), Chris@18: '#maxlength' => UserInterface::USERNAME_MAX_LENGTH, Chris@0: '#description' => $this->t("Several special characters are allowed, including space, period (.), hyphen (-), apostrophe ('), underscore (_), and the @ sign."), Chris@0: '#required' => TRUE, Chris@0: '#attributes' => [ Chris@0: 'class' => ['username'], Chris@0: 'autocorrect' => 'off', Chris@0: 'autocapitalize' => 'off', Chris@0: 'spellcheck' => 'false', Chris@0: ], Chris@0: '#default_value' => (!$register ? $account->getAccountName() : ''), Chris@18: '#access' => $account->name->access('edit'), Chris@0: ]; Chris@0: Chris@0: // Display password field only for existing users or when user is allowed to Chris@0: // assign a password during registration. Chris@0: if (!$register) { Chris@0: $form['account']['pass'] = [ Chris@0: '#type' => 'password_confirm', Chris@0: '#size' => 25, Chris@0: '#description' => $this->t('To change the current user password, enter the new password in both fields.'), Chris@0: ]; Chris@0: Chris@0: // To skip the current password field, the user must have logged in via a Chris@0: // one-time link and have the token in the URL. Store this in $form_state Chris@0: // so it persists even on subsequent Ajax requests. Chris@0: if (!$form_state->get('user_pass_reset') && ($token = $this->getRequest()->get('pass-reset-token'))) { Chris@0: $session_key = 'pass_reset_' . $account->id(); Chris@0: $user_pass_reset = isset($_SESSION[$session_key]) && Crypt::hashEquals($_SESSION[$session_key], $token); Chris@0: $form_state->set('user_pass_reset', $user_pass_reset); Chris@0: } Chris@0: Chris@0: // The user must enter their current password to change to a new one. Chris@0: if ($user->id() == $account->id()) { Chris@0: $form['account']['current_pass'] = [ Chris@0: '#type' => 'password', Chris@0: '#title' => $this->t('Current password'), Chris@0: '#size' => 25, Chris@0: '#access' => !$form_state->get('user_pass_reset'), Chris@0: '#weight' => -5, Chris@0: // Do not let web browsers remember this password, since we are Chris@0: // trying to confirm that the person submitting the form actually Chris@0: // knows the current one. Chris@0: '#attributes' => ['autocomplete' => 'off'], Chris@0: ]; Chris@0: $form_state->set('user', $account); Chris@0: Chris@0: // The user may only change their own password without their current Chris@0: // password if they logged in via a one-time login link. Chris@0: if (!$form_state->get('user_pass_reset')) { Chris@0: $form['account']['current_pass']['#description'] = $this->t('Required if you want to change the %mail or %pass below. Reset your password.', [ Chris@0: '%mail' => $form['account']['mail']['#title'], Chris@0: '%pass' => $this->t('Password'), Chris@0: ':request_new_url' => $this->url('user.pass'), Chris@0: ]); Chris@0: } Chris@0: } Chris@0: } Chris@18: elseif (!$config->get('verify_mail') || $admin_create) { Chris@0: $form['account']['pass'] = [ Chris@0: '#type' => 'password_confirm', Chris@0: '#size' => 25, Chris@0: '#description' => $this->t('Provide a password for the new account in both fields.'), Chris@0: '#required' => TRUE, Chris@0: ]; Chris@0: } Chris@0: Chris@0: // When not building the user registration form, prevent web browsers from Chris@0: // autofilling/prefilling the email, username, and password fields. Chris@17: if (!$register) { Chris@0: foreach (['mail', 'name', 'pass'] as $key) { Chris@0: if (isset($form['account'][$key])) { Chris@0: $form['account'][$key]['#attributes']['autocomplete'] = 'off'; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@18: if (!$self_register) { Chris@0: $status = $account->get('status')->value; Chris@0: } Chris@0: else { Chris@18: $status = $config->get('register') == UserInterface::REGISTER_VISITORS ? 1 : 0; Chris@0: } Chris@0: Chris@0: $form['account']['status'] = [ Chris@0: '#type' => 'radios', Chris@0: '#title' => $this->t('Status'), Chris@0: '#default_value' => $status, Chris@0: '#options' => [$this->t('Blocked'), $this->t('Active')], Chris@18: '#access' => $account->status->access('edit'), Chris@0: ]; Chris@0: Chris@0: $roles = array_map(['\Drupal\Component\Utility\Html', 'escape'], user_role_names(TRUE)); Chris@0: Chris@0: $form['account']['roles'] = [ Chris@0: '#type' => 'checkboxes', Chris@0: '#title' => $this->t('Roles'), Chris@0: '#default_value' => (!$register ? $account->getRoles() : []), Chris@0: '#options' => $roles, Chris@0: '#access' => $roles && $user->hasPermission('administer permissions'), Chris@0: ]; Chris@0: Chris@0: // Special handling for the inevitable "Authenticated user" role. Chris@0: $form['account']['roles'][RoleInterface::AUTHENTICATED_ID] = [ Chris@0: '#default_value' => TRUE, Chris@0: '#disabled' => TRUE, Chris@0: ]; Chris@0: Chris@0: $form['account']['notify'] = [ Chris@0: '#type' => 'checkbox', Chris@0: '#title' => $this->t('Notify user of new account'), Chris@18: '#access' => $admin_create, Chris@0: ]; Chris@0: Chris@0: $user_preferred_langcode = $register ? $language_interface->getId() : $account->getPreferredLangcode(); Chris@0: Chris@0: $user_preferred_admin_langcode = $register ? $language_interface->getId() : $account->getPreferredAdminLangcode(FALSE); Chris@0: Chris@0: // Is the user preferred language added? Chris@0: $user_language_added = FALSE; Chris@0: if ($this->languageManager instanceof ConfigurableLanguageManagerInterface) { Chris@0: $negotiator = $this->languageManager->getNegotiator(); Chris@0: $user_language_added = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUser::METHOD_ID, LanguageInterface::TYPE_INTERFACE); Chris@0: } Chris@0: $form['language'] = [ Chris@0: '#type' => $this->languageManager->isMultilingual() ? 'details' : 'container', Chris@0: '#title' => $this->t('Language settings'), Chris@0: '#open' => TRUE, Chris@0: // Display language selector when either creating a user on the admin Chris@0: // interface or editing a user account. Chris@18: '#access' => !$self_register, Chris@0: ]; Chris@0: Chris@0: $form['language']['preferred_langcode'] = [ Chris@0: '#type' => 'language_select', Chris@0: '#title' => $this->t('Site language'), Chris@0: '#languages' => LanguageInterface::STATE_CONFIGURABLE, Chris@0: '#default_value' => $user_preferred_langcode, Chris@0: '#description' => $user_language_added ? $this->t("This account's preferred language for emails and site presentation.") : $this->t("This account's preferred language for emails."), Chris@0: // This is used to explain that user preferred language and entity Chris@0: // language are synchronized. It can be removed if a different behavior is Chris@0: // desired. Chris@0: '#pre_render' => ['user_langcode' => [$this, 'alterPreferredLangcodeDescription']], Chris@0: ]; Chris@0: Chris@0: // Only show the account setting for Administration pages language to users Chris@0: // if one of the detection and selection methods uses it. Chris@0: $show_admin_language = FALSE; Chris@0: if ($account->hasPermission('access administration pages') && $this->languageManager instanceof ConfigurableLanguageManagerInterface) { Chris@0: $negotiator = $this->languageManager->getNegotiator(); Chris@0: $show_admin_language = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUserAdmin::METHOD_ID); Chris@0: } Chris@0: $form['language']['preferred_admin_langcode'] = [ Chris@0: '#type' => 'language_select', Chris@0: '#title' => $this->t('Administration pages language'), Chris@0: '#languages' => LanguageInterface::STATE_CONFIGURABLE, Chris@0: '#default_value' => $user_preferred_admin_langcode, Chris@0: '#access' => $show_admin_language, Chris@0: '#empty_option' => $this->t('- No preference -'), Chris@0: '#empty_value' => '', Chris@0: ]; Chris@0: Chris@0: // User entities contain both a langcode property (for identifying the Chris@0: // language of the entity data) and a preferred_langcode property (see Chris@0: // above). Rather than provide a UI forcing the user to choose both Chris@0: // separately, assume that the user profile data is in the user's preferred Chris@0: // language. This entity builder provides that synchronization. For Chris@0: // use-cases where this synchronization is not desired, a module can alter Chris@0: // or remove this item. Chris@0: $form['#entity_builders']['sync_user_langcode'] = '::syncUserLangcode'; Chris@0: Chris@0: return parent::form($form, $form_state, $account); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Alters the preferred language widget description. Chris@0: * Chris@0: * @param array $element Chris@0: * The preferred language form element. Chris@0: * Chris@0: * @return array Chris@0: * The preferred language form element. Chris@0: */ Chris@0: public function alterPreferredLangcodeDescription(array $element) { Chris@0: // Only add to the description if the form element has a description. Chris@0: if (isset($element['#description'])) { Chris@0: $element['#description'] .= ' ' . $this->t("This is also assumed to be the primary language of this account's profile information."); Chris@0: } Chris@0: return $element; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Synchronizes preferred language and entity language. Chris@0: * Chris@0: * @param string $entity_type_id Chris@0: * The entity type identifier. Chris@0: * @param \Drupal\user\UserInterface $user Chris@0: * The entity updated with the submitted values. Chris@0: * @param array $form Chris@0: * The complete form array. Chris@0: * @param \Drupal\Core\Form\FormStateInterface $form_state Chris@0: * The current state of the form. Chris@0: */ Chris@0: public function syncUserLangcode($entity_type_id, UserInterface $user, array &$form, FormStateInterface &$form_state) { Chris@0: $user->getUntranslated()->langcode = $user->preferred_langcode; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function buildEntity(array $form, FormStateInterface $form_state) { Chris@0: // Change the roles array to a list of enabled roles. Chris@0: // @todo: Alter the form state as the form values are directly extracted and Chris@0: // set on the field, which throws an exception as the list requires Chris@0: // numeric keys. Allow to override this per field. As this function is Chris@0: // called twice, we have to prevent it from getting the array keys twice. Chris@0: Chris@0: if (is_string(key($form_state->getValue('roles')))) { Chris@0: $form_state->setValue('roles', array_keys(array_filter($form_state->getValue('roles')))); Chris@0: } Chris@0: Chris@0: /** @var \Drupal\user\UserInterface $account */ Chris@0: $account = parent::buildEntity($form, $form_state); Chris@0: Chris@0: // Translate the empty value '' of language selects to an unset field. Chris@0: foreach (['preferred_langcode', 'preferred_admin_langcode'] as $field_name) { Chris@0: if ($form_state->getValue($field_name) === '') { Chris@0: $account->$field_name = NULL; Chris@0: } Chris@0: } Chris@0: Chris@0: // Set existing password if set in the form state. Chris@0: $current_pass = trim($form_state->getValue('current_pass')); Chris@0: if (strlen($current_pass) > 0) { Chris@0: $account->setExistingPassword($current_pass); Chris@0: } Chris@0: Chris@0: // Skip the protected user field constraint if the user came from the Chris@0: // password recovery page. Chris@0: $account->_skipProtectedUserFieldConstraint = $form_state->get('user_pass_reset'); Chris@0: Chris@0: return $account; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: protected function getEditedFieldNames(FormStateInterface $form_state) { Chris@0: return array_merge([ Chris@0: 'name', Chris@0: 'pass', Chris@0: 'mail', Chris@0: 'timezone', Chris@0: 'langcode', Chris@0: 'preferred_langcode', Chris@17: 'preferred_admin_langcode', Chris@0: ], parent::getEditedFieldNames($form_state)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) { Chris@0: // Manually flag violations of fields not handled by the form display. This Chris@0: // is necessary as entity form displays only flag violations for fields Chris@0: // contained in the display. Chris@0: $field_names = [ Chris@0: 'name', Chris@0: 'pass', Chris@0: 'mail', Chris@0: 'timezone', Chris@0: 'langcode', Chris@0: 'preferred_langcode', Chris@17: 'preferred_admin_langcode', Chris@0: ]; Chris@0: foreach ($violations->getByFields($field_names) as $violation) { Chris@0: list($field_name) = explode('.', $violation->getPropertyPath(), 2); Chris@0: $form_state->setErrorByName($field_name, $violation->getMessage()); Chris@0: } Chris@0: parent::flagViolations($violations, $form, $form_state); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function submitForm(array &$form, FormStateInterface $form_state) { Chris@0: parent::submitForm($form, $form_state); Chris@0: Chris@0: $user = $this->getEntity($form_state); Chris@0: // If there's a session set to the users id, remove the password reset tag Chris@0: // since a new password was saved. Chris@0: if (isset($_SESSION['pass_reset_' . $user->id()])) { Chris@0: unset($_SESSION['pass_reset_' . $user->id()]); Chris@0: } Chris@0: } Chris@0: Chris@0: }