5 use Drupal\Component\Datetime\TimeInterface;
6 use Drupal\Component\Utility\Crypt;
7 use Drupal\Core\Entity\ContentEntityForm;
8 use Drupal\Core\Entity\EntityConstraintViolationListInterface;
9 use Drupal\Core\Entity\EntityManagerInterface;
10 use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
11 use Drupal\Core\Form\FormStateInterface;
12 use Drupal\Core\Language\LanguageInterface;
13 use Drupal\Core\Language\LanguageManagerInterface;
14 use Drupal\language\ConfigurableLanguageManagerInterface;
15 use Drupal\user\Plugin\LanguageNegotiation\LanguageNegotiationUser;
16 use Drupal\user\Plugin\LanguageNegotiation\LanguageNegotiationUserAdmin;
17 use Symfony\Component\DependencyInjection\ContainerInterface;
20 * Form controller for the user account forms.
22 abstract class AccountForm extends ContentEntityForm {
25 * The language manager.
27 * @var \Drupal\Core\Language\LanguageManagerInterface
29 protected $languageManager;
32 * Constructs a new EntityForm object.
34 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
36 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
37 * The language manager.
38 * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
39 * The entity type bundle service.
40 * @param \Drupal\Component\Datetime\TimeInterface $time
43 public function __construct(EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL) {
44 parent::__construct($entity_manager, $entity_type_bundle_info, $time);
45 $this->languageManager = $language_manager;
51 public static function create(ContainerInterface $container) {
53 $container->get('entity.manager'),
54 $container->get('language_manager'),
55 $container->get('entity_type.bundle.info'),
56 $container->get('datetime.time')
63 public function form(array $form, FormStateInterface $form_state) {
64 /** @var \Drupal\user\UserInterface $account */
65 $account = $this->entity;
66 $user = $this->currentUser();
67 $config = \Drupal::config('user.settings');
68 $form['#cache']['tags'] = $config->getCacheTags();
70 $language_interface = \Drupal::languageManager()->getCurrentLanguage();
71 $register = $account->isAnonymous();
72 $admin = $user->hasPermission('administer users');
74 // Account information.
76 '#type' => 'container',
80 // The mail field is NOT required if account originally had no mail set
81 // and the user performing the edit has 'administer users' permission.
82 // This allows users without email address to be edited and deleted.
83 // Also see \Drupal\user\Plugin\Validation\Constraint\UserMailRequired.
84 $form['account']['mail'] = [
86 '#title' => $this->t('Email address'),
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.'),
88 '#required' => !(!$account->getEmail() && $admin),
89 '#default_value' => (!$register ? $account->getEmail() : ''),
92 // Only show name field on registration form or user can change own username.
93 $form['account']['name'] = [
94 '#type' => 'textfield',
95 '#title' => $this->t('Username'),
96 '#maxlength' => USERNAME_MAX_LENGTH,
97 '#description' => $this->t("Several special characters are allowed, including space, period (.), hyphen (-), apostrophe ('), underscore (_), and the @ sign."),
100 'class' => ['username'],
101 'autocorrect' => 'off',
102 'autocapitalize' => 'off',
103 'spellcheck' => 'false',
105 '#default_value' => (!$register ? $account->getAccountName() : ''),
106 '#access' => ($register || ($user->id() == $account->id() && $user->hasPermission('change own username')) || $admin),
109 // Display password field only for existing users or when user is allowed to
110 // assign a password during registration.
112 $form['account']['pass'] = [
113 '#type' => 'password_confirm',
115 '#description' => $this->t('To change the current user password, enter the new password in both fields.'),
118 // To skip the current password field, the user must have logged in via a
119 // one-time link and have the token in the URL. Store this in $form_state
120 // so it persists even on subsequent Ajax requests.
121 if (!$form_state->get('user_pass_reset') && ($token = $this->getRequest()->get('pass-reset-token'))) {
122 $session_key = 'pass_reset_' . $account->id();
123 $user_pass_reset = isset($_SESSION[$session_key]) && Crypt::hashEquals($_SESSION[$session_key], $token);
124 $form_state->set('user_pass_reset', $user_pass_reset);
127 // The user must enter their current password to change to a new one.
128 if ($user->id() == $account->id()) {
129 $form['account']['current_pass'] = [
130 '#type' => 'password',
131 '#title' => $this->t('Current password'),
133 '#access' => !$form_state->get('user_pass_reset'),
135 // Do not let web browsers remember this password, since we are
136 // trying to confirm that the person submitting the form actually
137 // knows the current one.
138 '#attributes' => ['autocomplete' => 'off'],
140 $form_state->set('user', $account);
142 // The user may only change their own password without their current
143 // password if they logged in via a one-time login link.
144 if (!$form_state->get('user_pass_reset')) {
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>.', [
146 '%mail' => $form['account']['mail']['#title'],
147 '%pass' => $this->t('Password'),
148 ':request_new_url' => $this->url('user.pass'),
153 elseif (!$config->get('verify_mail') || $admin) {
154 $form['account']['pass'] = [
155 '#type' => 'password_confirm',
157 '#description' => $this->t('Provide a password for the new account in both fields.'),
162 // When not building the user registration form, prevent web browsers from
163 // autofilling/prefilling the email, username, and password fields.
164 if ($this->getOperation() != 'register') {
165 foreach (['mail', 'name', 'pass'] as $key) {
166 if (isset($form['account'][$key])) {
167 $form['account'][$key]['#attributes']['autocomplete'] = 'off';
172 if ($admin || !$register) {
173 $status = $account->get('status')->value;
176 $status = $config->get('register') == USER_REGISTER_VISITORS ? 1 : 0;
179 $form['account']['status'] = [
181 '#title' => $this->t('Status'),
182 '#default_value' => $status,
183 '#options' => [$this->t('Blocked'), $this->t('Active')],
187 $roles = array_map(['\Drupal\Component\Utility\Html', 'escape'], user_role_names(TRUE));
189 $form['account']['roles'] = [
190 '#type' => 'checkboxes',
191 '#title' => $this->t('Roles'),
192 '#default_value' => (!$register ? $account->getRoles() : []),
193 '#options' => $roles,
194 '#access' => $roles && $user->hasPermission('administer permissions'),
197 // Special handling for the inevitable "Authenticated user" role.
198 $form['account']['roles'][RoleInterface::AUTHENTICATED_ID] = [
199 '#default_value' => TRUE,
203 $form['account']['notify'] = [
204 '#type' => 'checkbox',
205 '#title' => $this->t('Notify user of new account'),
206 '#access' => $register && $admin,
209 $user_preferred_langcode = $register ? $language_interface->getId() : $account->getPreferredLangcode();
211 $user_preferred_admin_langcode = $register ? $language_interface->getId() : $account->getPreferredAdminLangcode(FALSE);
213 // Is the user preferred language added?
214 $user_language_added = FALSE;
215 if ($this->languageManager instanceof ConfigurableLanguageManagerInterface) {
216 $negotiator = $this->languageManager->getNegotiator();
217 $user_language_added = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUser::METHOD_ID, LanguageInterface::TYPE_INTERFACE);
219 $form['language'] = [
220 '#type' => $this->languageManager->isMultilingual() ? 'details' : 'container',
221 '#title' => $this->t('Language settings'),
223 // Display language selector when either creating a user on the admin
224 // interface or editing a user account.
225 '#access' => !$register || $admin,
228 $form['language']['preferred_langcode'] = [
229 '#type' => 'language_select',
230 '#title' => $this->t('Site language'),
231 '#languages' => LanguageInterface::STATE_CONFIGURABLE,
232 '#default_value' => $user_preferred_langcode,
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."),
234 // This is used to explain that user preferred language and entity
235 // language are synchronized. It can be removed if a different behavior is
237 '#pre_render' => ['user_langcode' => [$this, 'alterPreferredLangcodeDescription']],
240 // Only show the account setting for Administration pages language to users
241 // if one of the detection and selection methods uses it.
242 $show_admin_language = FALSE;
243 if ($account->hasPermission('access administration pages') && $this->languageManager instanceof ConfigurableLanguageManagerInterface) {
244 $negotiator = $this->languageManager->getNegotiator();
245 $show_admin_language = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUserAdmin::METHOD_ID);
247 $form['language']['preferred_admin_langcode'] = [
248 '#type' => 'language_select',
249 '#title' => $this->t('Administration pages language'),
250 '#languages' => LanguageInterface::STATE_CONFIGURABLE,
251 '#default_value' => $user_preferred_admin_langcode,
252 '#access' => $show_admin_language,
253 '#empty_option' => $this->t('- No preference -'),
254 '#empty_value' => '',
257 // User entities contain both a langcode property (for identifying the
258 // language of the entity data) and a preferred_langcode property (see
259 // above). Rather than provide a UI forcing the user to choose both
260 // separately, assume that the user profile data is in the user's preferred
261 // language. This entity builder provides that synchronization. For
262 // use-cases where this synchronization is not desired, a module can alter
263 // or remove this item.
264 $form['#entity_builders']['sync_user_langcode'] = '::syncUserLangcode';
266 return parent::form($form, $form_state, $account);
270 * Alters the preferred language widget description.
272 * @param array $element
273 * The preferred language form element.
276 * The preferred language form element.
278 public function alterPreferredLangcodeDescription(array $element) {
279 // Only add to the description if the form element has a description.
280 if (isset($element['#description'])) {
281 $element['#description'] .= ' ' . $this->t("This is also assumed to be the primary language of this account's profile information.");
287 * Synchronizes preferred language and entity language.
289 * @param string $entity_type_id
290 * The entity type identifier.
291 * @param \Drupal\user\UserInterface $user
292 * The entity updated with the submitted values.
294 * The complete form array.
295 * @param \Drupal\Core\Form\FormStateInterface $form_state
296 * The current state of the form.
298 public function syncUserLangcode($entity_type_id, UserInterface $user, array &$form, FormStateInterface &$form_state) {
299 $user->getUntranslated()->langcode = $user->preferred_langcode;
305 public function buildEntity(array $form, FormStateInterface $form_state) {
306 // Change the roles array to a list of enabled roles.
307 // @todo: Alter the form state as the form values are directly extracted and
308 // set on the field, which throws an exception as the list requires
309 // numeric keys. Allow to override this per field. As this function is
310 // called twice, we have to prevent it from getting the array keys twice.
312 if (is_string(key($form_state->getValue('roles')))) {
313 $form_state->setValue('roles', array_keys(array_filter($form_state->getValue('roles'))));
316 /** @var \Drupal\user\UserInterface $account */
317 $account = parent::buildEntity($form, $form_state);
319 // Translate the empty value '' of language selects to an unset field.
320 foreach (['preferred_langcode', 'preferred_admin_langcode'] as $field_name) {
321 if ($form_state->getValue($field_name) === '') {
322 $account->$field_name = NULL;
326 // Set existing password if set in the form state.
327 $current_pass = trim($form_state->getValue('current_pass'));
328 if (strlen($current_pass) > 0) {
329 $account->setExistingPassword($current_pass);
332 // Skip the protected user field constraint if the user came from the
333 // password recovery page.
334 $account->_skipProtectedUserFieldConstraint = $form_state->get('user_pass_reset');
342 protected function getEditedFieldNames(FormStateInterface $form_state) {
349 'preferred_langcode',
350 'preferred_admin_langcode'
351 ], parent::getEditedFieldNames($form_state));
357 protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
358 // Manually flag violations of fields not handled by the form display. This
359 // is necessary as entity form displays only flag violations for fields
360 // contained in the display.
367 'preferred_langcode',
368 'preferred_admin_langcode'
370 foreach ($violations->getByFields($field_names) as $violation) {
371 list($field_name) = explode('.', $violation->getPropertyPath(), 2);
372 $form_state->setErrorByName($field_name, $violation->getMessage());
374 parent::flagViolations($violations, $form, $form_state);
380 public function submitForm(array &$form, FormStateInterface $form_state) {
381 parent::submitForm($form, $form_state);
383 $user = $this->getEntity($form_state);
384 // If there's a session set to the users id, remove the password reset tag
385 // since a new password was saved.
386 if (isset($_SESSION['pass_reset_' . $user->id()])) {
387 unset($_SESSION['pass_reset_' . $user->id()]);