3 namespace Drupal\devel\Form;
5 use Drupal\Core\Access\CsrfTokenGenerator;
6 use Drupal\Core\Form\FormBase;
7 use Drupal\Core\Form\FormStateInterface;
9 use Drupal\user\Entity\User;
10 use Symfony\Component\DependencyInjection\ContainerInterface;
13 * Defines a form that allows privileged users to generate entities.
15 class SwitchUserForm extends FormBase {
18 * The csrf token generator.
20 * @var \Drupal\Core\Access\CsrfTokenGenerator
25 * Constructs a new SwitchUserForm object.
27 * @param \Drupal\Core\Access\CsrfTokenGenerator $csrf_token_generator
29 public function __construct(CsrfTokenGenerator $csrf_token_generator) {
30 $this->csrfToken = $csrf_token_generator;
36 public static function create(ContainerInterface $container) {
38 $container->get('csrf_token')
45 public function getFormId() {
46 return 'devel_switchuser_form';
52 public function buildForm(array $form, FormStateInterface $form_state) {
53 $form['autocomplete'] = [
54 '#type' => 'container',
56 'class' => ['container-inline'],
59 $form['autocomplete']['userid'] = [
60 '#type' => 'entity_autocomplete',
61 '#title' => $this->t('Username'),
62 '#placeholder' => $this->t('Enter username'),
63 '#target_type' => 'user',
64 '#selection_settings' => [
65 'include_anonymous' => FALSE
67 '#process_default_value' => FALSE,
68 '#maxlength' => USERNAME_MAX_LENGTH,
69 '#title_display' => 'invisible',
74 $form['autocomplete']['actions'] = ['#type' => 'actions'];
75 $form['autocomplete']['actions']['submit'] = [
77 '#value' => $this->t('Switch'),
86 public function validateForm(array &$form, FormStateInterface $form_state) {
87 if (!$account = User::load($form_state->getValue('userid'))) {
88 $form_state->setErrorByName('userid', $this->t('Username not found'));
91 $form_state->setValue('username', $account->getAccountName());
98 public function submitForm(array &$form, FormStateInterface $form_state) {
99 // We cannot rely on automatic token creation, since the csrf seed changes
100 // after the redirect and the generated token is not more valid.
101 // TODO find another way to do this.
102 $url = Url::fromRoute('devel.switch', ['name' => $form_state->getValue('username')]);
103 $url->setOption('query', ['token' => $this->csrfToken->get($url->getInternalPath())]);
105 $form_state->setRedirectUrl($url);