1

I'm displaying a form using the Form API under a given URL. User gets this URL and accesses it. But before the user fills out the form, they need to be registered or logged in.

How can I send the user to the login page, or present the login form, then subsequently direct them back to the form under the given URL?

This is not a Webform -- I'm using the Form API.

0

1 Answer 1

5

Redirect to the login page and provide a destination query parameter to the current route to redirect back after login:

  public function buildForm(array $form, FormStateInterface $form_state) {
    if ($this->currentUser()->isAnonymous()) {
      return $this->redirect(
          'user.login',
          [],
          ['query' => ['destination' => Url::fromRoute('<current>')->toString()]]
      );
    }

    // build form

    return $form
  }

Don't forget to add a use Drupal\Core\Url; statement to the class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.