1. 8.3.x core/modules/user/src/AccountForm.php
  2. 8.0.x core/modules/user/src/AccountForm.php
  3. 8.1.x core/modules/user/src/AccountForm.php
  4. 8.2.x core/modules/user/src/AccountForm.php
  5. 8.4.x core/modules/user/src/AccountForm.php

Namespace

Drupal\user

File

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

Classes

Namesort descending Description
AccountForm Form controller for the user account forms.