How to to redirect a form to a certain node for anonymous users? In a custom module, I have a form that is triggered by an option in a menu.
I'd want this form to be redirected automatically (without action of the user) to a certain node (/node/2) when the user is not authenticated.
In the public function buildForm(array $form, FormStateInterface $form_state) {, I know how to not display the fields of the form for the anonymous user:  

$oCurrentUser = \Drupal::currentUser();
if ($oCurrentUser-&gt;isAnonymous()) {
} else {

some fields...    

$form['submit'] = [
  '#type' =&gt; 'submit',
  '#value' =&gt; $this-&gt;t('Submit'),
];
return $form;
}


I guess that redirection might be done with   $form_state-&gt;setRedirect('entity.node.canonical', ['node' =&gt; 2]);
but I don't know how to make it work...
Any idea?
In buildForm() you can return a redirect response the same way as in a controller:

  public function buildForm(array $form, FormStateInterface $form_state) {
    if ($this-&gt;currentUser()-&gt;isAnonymous()) {
      return $this-&gt;redirect('entity.node.canonical', ['node' =&gt; 2]);
    }

    // build $form for authenticated users

    return $form;
  }


Use $form_state-&gt;setRedirect() if you want to redirect in a form submit handler.



Using buildForm() as controller by specifying _form instead of _controller is documented and widely used (not in FormInterface, but on DO: https://www.drupal.org/docs/8/api/routing-system). It's unlikely core will ask devs to replace it by their own controller.