annotate core/modules/user/src/AccountForm.php @ 17:129ea1e6d783

Update, including to Drupal core 8.6.10
author Chris Cannam
date Thu, 28 Feb 2019 13:21:36 +0000
parents 4c8ae668cc8c
children af1871eacc83
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\user;
Chris@0 4
Chris@0 5 use Drupal\Component\Datetime\TimeInterface;
Chris@0 6 use Drupal\Component\Utility\Crypt;
Chris@0 7 use Drupal\Core\Entity\ContentEntityForm;
Chris@0 8 use Drupal\Core\Entity\EntityConstraintViolationListInterface;
Chris@17 9 use Drupal\Core\Entity\EntityRepositoryInterface;
Chris@0 10 use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
Chris@0 11 use Drupal\Core\Form\FormStateInterface;
Chris@0 12 use Drupal\Core\Language\LanguageInterface;
Chris@0 13 use Drupal\Core\Language\LanguageManagerInterface;
Chris@0 14 use Drupal\language\ConfigurableLanguageManagerInterface;
Chris@0 15 use Drupal\user\Plugin\LanguageNegotiation\LanguageNegotiationUser;
Chris@0 16 use Drupal\user\Plugin\LanguageNegotiation\LanguageNegotiationUserAdmin;
Chris@0 17 use Symfony\Component\DependencyInjection\ContainerInterface;
Chris@0 18
Chris@0 19 /**
Chris@0 20 * Form controller for the user account forms.
Chris@0 21 */
Chris@0 22 abstract class AccountForm extends ContentEntityForm {
Chris@0 23
Chris@0 24 /**
Chris@0 25 * The language manager.
Chris@0 26 *
Chris@0 27 * @var \Drupal\Core\Language\LanguageManagerInterface
Chris@0 28 */
Chris@0 29 protected $languageManager;
Chris@0 30
Chris@0 31 /**
Chris@0 32 * Constructs a new EntityForm object.
Chris@0 33 *
Chris@17 34 * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
Chris@17 35 * The entity repository.
Chris@0 36 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
Chris@0 37 * The language manager.
Chris@0 38 * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
Chris@0 39 * The entity type bundle service.
Chris@0 40 * @param \Drupal\Component\Datetime\TimeInterface $time
Chris@0 41 * The time service.
Chris@0 42 */
Chris@17 43 public function __construct(EntityRepositoryInterface $entity_repository, LanguageManagerInterface $language_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL) {
Chris@17 44 parent::__construct($entity_repository, $entity_type_bundle_info, $time);
Chris@0 45 $this->languageManager = $language_manager;
Chris@0 46 }
Chris@0 47
Chris@0 48 /**
Chris@0 49 * {@inheritdoc}
Chris@0 50 */
Chris@0 51 public static function create(ContainerInterface $container) {
Chris@0 52 return new static(
Chris@17 53 $container->get('entity.repository'),
Chris@0 54 $container->get('language_manager'),
Chris@0 55 $container->get('entity_type.bundle.info'),
Chris@0 56 $container->get('datetime.time')
Chris@0 57 );
Chris@0 58 }
Chris@0 59
Chris@0 60 /**
Chris@0 61 * {@inheritdoc}
Chris@0 62 */
Chris@0 63 public function form(array $form, FormStateInterface $form_state) {
Chris@0 64 /** @var \Drupal\user\UserInterface $account */
Chris@0 65 $account = $this->entity;
Chris@0 66 $user = $this->currentUser();
Chris@0 67 $config = \Drupal::config('user.settings');
Chris@0 68 $form['#cache']['tags'] = $config->getCacheTags();
Chris@0 69
Chris@0 70 $language_interface = \Drupal::languageManager()->getCurrentLanguage();
Chris@0 71 $register = $account->isAnonymous();
Chris@0 72 $admin = $user->hasPermission('administer users');
Chris@0 73
Chris@0 74 // Account information.
Chris@0 75 $form['account'] = [
Chris@0 76 '#type' => 'container',
Chris@0 77 '#weight' => -10,
Chris@0 78 ];
Chris@0 79
Chris@0 80 // The mail field is NOT required if account originally had no mail set
Chris@0 81 // and the user performing the edit has 'administer users' permission.
Chris@0 82 // This allows users without email address to be edited and deleted.
Chris@0 83 // Also see \Drupal\user\Plugin\Validation\Constraint\UserMailRequired.
Chris@0 84 $form['account']['mail'] = [
Chris@0 85 '#type' => 'email',
Chris@0 86 '#title' => $this->t('Email address'),
Chris@0 87 '#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@0 88 '#required' => !(!$account->getEmail() && $admin),
Chris@0 89 '#default_value' => (!$register ? $account->getEmail() : ''),
Chris@0 90 ];
Chris@0 91
Chris@0 92 // Only show name field on registration form or user can change own username.
Chris@0 93 $form['account']['name'] = [
Chris@0 94 '#type' => 'textfield',
Chris@0 95 '#title' => $this->t('Username'),
Chris@0 96 '#maxlength' => USERNAME_MAX_LENGTH,
Chris@0 97 '#description' => $this->t("Several special characters are allowed, including space, period (.), hyphen (-), apostrophe ('), underscore (_), and the @ sign."),
Chris@0 98 '#required' => TRUE,
Chris@0 99 '#attributes' => [
Chris@0 100 'class' => ['username'],
Chris@0 101 'autocorrect' => 'off',
Chris@0 102 'autocapitalize' => 'off',
Chris@0 103 'spellcheck' => 'false',
Chris@0 104 ],
Chris@0 105 '#default_value' => (!$register ? $account->getAccountName() : ''),
Chris@0 106 '#access' => ($register || ($user->id() == $account->id() && $user->hasPermission('change own username')) || $admin),
Chris@0 107 ];
Chris@0 108
Chris@0 109 // Display password field only for existing users or when user is allowed to
Chris@0 110 // assign a password during registration.
Chris@0 111 if (!$register) {
Chris@0 112 $form['account']['pass'] = [
Chris@0 113 '#type' => 'password_confirm',
Chris@0 114 '#size' => 25,
Chris@0 115 '#description' => $this->t('To change the current user password, enter the new password in both fields.'),
Chris@0 116 ];
Chris@0 117
Chris@0 118 // To skip the current password field, the user must have logged in via a
Chris@0 119 // one-time link and have the token in the URL. Store this in $form_state
Chris@0 120 // so it persists even on subsequent Ajax requests.
Chris@0 121 if (!$form_state->get('user_pass_reset') && ($token = $this->getRequest()->get('pass-reset-token'))) {
Chris@0 122 $session_key = 'pass_reset_' . $account->id();
Chris@0 123 $user_pass_reset = isset($_SESSION[$session_key]) && Crypt::hashEquals($_SESSION[$session_key], $token);
Chris@0 124 $form_state->set('user_pass_reset', $user_pass_reset);
Chris@0 125 }
Chris@0 126
Chris@0 127 // The user must enter their current password to change to a new one.
Chris@0 128 if ($user->id() == $account->id()) {
Chris@0 129 $form['account']['current_pass'] = [
Chris@0 130 '#type' => 'password',
Chris@0 131 '#title' => $this->t('Current password'),
Chris@0 132 '#size' => 25,
Chris@0 133 '#access' => !$form_state->get('user_pass_reset'),
Chris@0 134 '#weight' => -5,
Chris@0 135 // Do not let web browsers remember this password, since we are
Chris@0 136 // trying to confirm that the person submitting the form actually
Chris@0 137 // knows the current one.
Chris@0 138 '#attributes' => ['autocomplete' => 'off'],
Chris@0 139 ];
Chris@0 140 $form_state->set('user', $account);
Chris@0 141
Chris@0 142 // The user may only change their own password without their current
Chris@0 143 // password if they logged in via a one-time login link.
Chris@0 144 if (!$form_state->get('user_pass_reset')) {
Chris@0 145 $form['account']['current_pass']['#description'] = $this->t('Required if you want to change the %mail or %pass below. <a href=":request_new_url" title="Send password reset instructions via email.">Reset your password</a>.', [
Chris@0 146 '%mail' => $form['account']['mail']['#title'],
Chris@0 147 '%pass' => $this->t('Password'),
Chris@0 148 ':request_new_url' => $this->url('user.pass'),
Chris@0 149 ]);
Chris@0 150 }
Chris@0 151 }
Chris@0 152 }
Chris@0 153 elseif (!$config->get('verify_mail') || $admin) {
Chris@0 154 $form['account']['pass'] = [
Chris@0 155 '#type' => 'password_confirm',
Chris@0 156 '#size' => 25,
Chris@0 157 '#description' => $this->t('Provide a password for the new account in both fields.'),
Chris@0 158 '#required' => TRUE,
Chris@0 159 ];
Chris@0 160 }
Chris@0 161
Chris@0 162 // When not building the user registration form, prevent web browsers from
Chris@0 163 // autofilling/prefilling the email, username, and password fields.
Chris@17 164 if (!$register) {
Chris@0 165 foreach (['mail', 'name', 'pass'] as $key) {
Chris@0 166 if (isset($form['account'][$key])) {
Chris@0 167 $form['account'][$key]['#attributes']['autocomplete'] = 'off';
Chris@0 168 }
Chris@0 169 }
Chris@0 170 }
Chris@0 171
Chris@0 172 if ($admin || !$register) {
Chris@0 173 $status = $account->get('status')->value;
Chris@0 174 }
Chris@0 175 else {
Chris@0 176 $status = $config->get('register') == USER_REGISTER_VISITORS ? 1 : 0;
Chris@0 177 }
Chris@0 178
Chris@0 179 $form['account']['status'] = [
Chris@0 180 '#type' => 'radios',
Chris@0 181 '#title' => $this->t('Status'),
Chris@0 182 '#default_value' => $status,
Chris@0 183 '#options' => [$this->t('Blocked'), $this->t('Active')],
Chris@0 184 '#access' => $admin,
Chris@0 185 ];
Chris@0 186
Chris@0 187 $roles = array_map(['\Drupal\Component\Utility\Html', 'escape'], user_role_names(TRUE));
Chris@0 188
Chris@0 189 $form['account']['roles'] = [
Chris@0 190 '#type' => 'checkboxes',
Chris@0 191 '#title' => $this->t('Roles'),
Chris@0 192 '#default_value' => (!$register ? $account->getRoles() : []),
Chris@0 193 '#options' => $roles,
Chris@0 194 '#access' => $roles && $user->hasPermission('administer permissions'),
Chris@0 195 ];
Chris@0 196
Chris@0 197 // Special handling for the inevitable "Authenticated user" role.
Chris@0 198 $form['account']['roles'][RoleInterface::AUTHENTICATED_ID] = [
Chris@0 199 '#default_value' => TRUE,
Chris@0 200 '#disabled' => TRUE,
Chris@0 201 ];
Chris@0 202
Chris@0 203 $form['account']['notify'] = [
Chris@0 204 '#type' => 'checkbox',
Chris@0 205 '#title' => $this->t('Notify user of new account'),
Chris@0 206 '#access' => $register && $admin,
Chris@0 207 ];
Chris@0 208
Chris@0 209 $user_preferred_langcode = $register ? $language_interface->getId() : $account->getPreferredLangcode();
Chris@0 210
Chris@0 211 $user_preferred_admin_langcode = $register ? $language_interface->getId() : $account->getPreferredAdminLangcode(FALSE);
Chris@0 212
Chris@0 213 // Is the user preferred language added?
Chris@0 214 $user_language_added = FALSE;
Chris@0 215 if ($this->languageManager instanceof ConfigurableLanguageManagerInterface) {
Chris@0 216 $negotiator = $this->languageManager->getNegotiator();
Chris@0 217 $user_language_added = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUser::METHOD_ID, LanguageInterface::TYPE_INTERFACE);
Chris@0 218 }
Chris@0 219 $form['language'] = [
Chris@0 220 '#type' => $this->languageManager->isMultilingual() ? 'details' : 'container',
Chris@0 221 '#title' => $this->t('Language settings'),
Chris@0 222 '#open' => TRUE,
Chris@0 223 // Display language selector when either creating a user on the admin
Chris@0 224 // interface or editing a user account.
Chris@0 225 '#access' => !$register || $admin,
Chris@0 226 ];
Chris@0 227
Chris@0 228 $form['language']['preferred_langcode'] = [
Chris@0 229 '#type' => 'language_select',
Chris@0 230 '#title' => $this->t('Site language'),
Chris@0 231 '#languages' => LanguageInterface::STATE_CONFIGURABLE,
Chris@0 232 '#default_value' => $user_preferred_langcode,
Chris@0 233 '#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 234 // This is used to explain that user preferred language and entity
Chris@0 235 // language are synchronized. It can be removed if a different behavior is
Chris@0 236 // desired.
Chris@0 237 '#pre_render' => ['user_langcode' => [$this, 'alterPreferredLangcodeDescription']],
Chris@0 238 ];
Chris@0 239
Chris@0 240 // Only show the account setting for Administration pages language to users
Chris@0 241 // if one of the detection and selection methods uses it.
Chris@0 242 $show_admin_language = FALSE;
Chris@0 243 if ($account->hasPermission('access administration pages') && $this->languageManager instanceof ConfigurableLanguageManagerInterface) {
Chris@0 244 $negotiator = $this->languageManager->getNegotiator();
Chris@0 245 $show_admin_language = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUserAdmin::METHOD_ID);
Chris@0 246 }
Chris@0 247 $form['language']['preferred_admin_langcode'] = [
Chris@0 248 '#type' => 'language_select',
Chris@0 249 '#title' => $this->t('Administration pages language'),
Chris@0 250 '#languages' => LanguageInterface::STATE_CONFIGURABLE,
Chris@0 251 '#default_value' => $user_preferred_admin_langcode,
Chris@0 252 '#access' => $show_admin_language,
Chris@0 253 '#empty_option' => $this->t('- No preference -'),
Chris@0 254 '#empty_value' => '',
Chris@0 255 ];
Chris@0 256
Chris@0 257 // User entities contain both a langcode property (for identifying the
Chris@0 258 // language of the entity data) and a preferred_langcode property (see
Chris@0 259 // above). Rather than provide a UI forcing the user to choose both
Chris@0 260 // separately, assume that the user profile data is in the user's preferred
Chris@0 261 // language. This entity builder provides that synchronization. For
Chris@0 262 // use-cases where this synchronization is not desired, a module can alter
Chris@0 263 // or remove this item.
Chris@0 264 $form['#entity_builders']['sync_user_langcode'] = '::syncUserLangcode';
Chris@0 265
Chris@0 266 return parent::form($form, $form_state, $account);
Chris@0 267 }
Chris@0 268
Chris@0 269 /**
Chris@0 270 * Alters the preferred language widget description.
Chris@0 271 *
Chris@0 272 * @param array $element
Chris@0 273 * The preferred language form element.
Chris@0 274 *
Chris@0 275 * @return array
Chris@0 276 * The preferred language form element.
Chris@0 277 */
Chris@0 278 public function alterPreferredLangcodeDescription(array $element) {
Chris@0 279 // Only add to the description if the form element has a description.
Chris@0 280 if (isset($element['#description'])) {
Chris@0 281 $element['#description'] .= ' ' . $this->t("This is also assumed to be the primary language of this account's profile information.");
Chris@0 282 }
Chris@0 283 return $element;
Chris@0 284 }
Chris@0 285
Chris@0 286 /**
Chris@0 287 * Synchronizes preferred language and entity language.
Chris@0 288 *
Chris@0 289 * @param string $entity_type_id
Chris@0 290 * The entity type identifier.
Chris@0 291 * @param \Drupal\user\UserInterface $user
Chris@0 292 * The entity updated with the submitted values.
Chris@0 293 * @param array $form
Chris@0 294 * The complete form array.
Chris@0 295 * @param \Drupal\Core\Form\FormStateInterface $form_state
Chris@0 296 * The current state of the form.
Chris@0 297 */
Chris@0 298 public function syncUserLangcode($entity_type_id, UserInterface $user, array &$form, FormStateInterface &$form_state) {
Chris@0 299 $user->getUntranslated()->langcode = $user->preferred_langcode;
Chris@0 300 }
Chris@0 301
Chris@0 302 /**
Chris@0 303 * {@inheritdoc}
Chris@0 304 */
Chris@0 305 public function buildEntity(array $form, FormStateInterface $form_state) {
Chris@0 306 // Change the roles array to a list of enabled roles.
Chris@0 307 // @todo: Alter the form state as the form values are directly extracted and
Chris@0 308 // set on the field, which throws an exception as the list requires
Chris@0 309 // numeric keys. Allow to override this per field. As this function is
Chris@0 310 // called twice, we have to prevent it from getting the array keys twice.
Chris@0 311
Chris@0 312 if (is_string(key($form_state->getValue('roles')))) {
Chris@0 313 $form_state->setValue('roles', array_keys(array_filter($form_state->getValue('roles'))));
Chris@0 314 }
Chris@0 315
Chris@0 316 /** @var \Drupal\user\UserInterface $account */
Chris@0 317 $account = parent::buildEntity($form, $form_state);
Chris@0 318
Chris@0 319 // Translate the empty value '' of language selects to an unset field.
Chris@0 320 foreach (['preferred_langcode', 'preferred_admin_langcode'] as $field_name) {
Chris@0 321 if ($form_state->getValue($field_name) === '') {
Chris@0 322 $account->$field_name = NULL;
Chris@0 323 }
Chris@0 324 }
Chris@0 325
Chris@0 326 // Set existing password if set in the form state.
Chris@0 327 $current_pass = trim($form_state->getValue('current_pass'));
Chris@0 328 if (strlen($current_pass) > 0) {
Chris@0 329 $account->setExistingPassword($current_pass);
Chris@0 330 }
Chris@0 331
Chris@0 332 // Skip the protected user field constraint if the user came from the
Chris@0 333 // password recovery page.
Chris@0 334 $account->_skipProtectedUserFieldConstraint = $form_state->get('user_pass_reset');
Chris@0 335
Chris@0 336 return $account;
Chris@0 337 }
Chris@0 338
Chris@0 339 /**
Chris@0 340 * {@inheritdoc}
Chris@0 341 */
Chris@0 342 protected function getEditedFieldNames(FormStateInterface $form_state) {
Chris@0 343 return array_merge([
Chris@0 344 'name',
Chris@0 345 'pass',
Chris@0 346 'mail',
Chris@0 347 'timezone',
Chris@0 348 'langcode',
Chris@0 349 'preferred_langcode',
Chris@17 350 'preferred_admin_langcode',
Chris@0 351 ], parent::getEditedFieldNames($form_state));
Chris@0 352 }
Chris@0 353
Chris@0 354 /**
Chris@0 355 * {@inheritdoc}
Chris@0 356 */
Chris@0 357 protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
Chris@0 358 // Manually flag violations of fields not handled by the form display. This
Chris@0 359 // is necessary as entity form displays only flag violations for fields
Chris@0 360 // contained in the display.
Chris@0 361 $field_names = [
Chris@0 362 'name',
Chris@0 363 'pass',
Chris@0 364 'mail',
Chris@0 365 'timezone',
Chris@0 366 'langcode',
Chris@0 367 'preferred_langcode',
Chris@17 368 'preferred_admin_langcode',
Chris@0 369 ];
Chris@0 370 foreach ($violations->getByFields($field_names) as $violation) {
Chris@0 371 list($field_name) = explode('.', $violation->getPropertyPath(), 2);
Chris@0 372 $form_state->setErrorByName($field_name, $violation->getMessage());
Chris@0 373 }
Chris@0 374 parent::flagViolations($violations, $form, $form_state);
Chris@0 375 }
Chris@0 376
Chris@0 377 /**
Chris@0 378 * {@inheritdoc}
Chris@0 379 */
Chris@0 380 public function submitForm(array &$form, FormStateInterface $form_state) {
Chris@0 381 parent::submitForm($form, $form_state);
Chris@0 382
Chris@0 383 $user = $this->getEntity($form_state);
Chris@0 384 // If there's a session set to the users id, remove the password reset tag
Chris@0 385 // since a new password was saved.
Chris@0 386 if (isset($_SESSION['pass_reset_' . $user->id()])) {
Chris@0 387 unset($_SESSION['pass_reset_' . $user->id()]);
Chris@0 388 }
Chris@0 389 }
Chris@0 390
Chris@0 391 }