Form Redirect before submit? I have a form which has 2 values prefilled (values come from a few steps the user has to take to be given the chance to get to the form I'm talking about).
My question is, how do I redirect the user back to step 1 when the form loads if the values are not present?
I have a hook_form_alter() and I have the logic to check whether or not the session variables are set but I cannot seem to redirect. Tried return new RedirectResponse($url) and return new TrustedRedirectResponse($url) also I've checked with the debugger to see if the returns are called and they are but the redirect is not happening and I get to the form when I should not be able to.
If it helps, it is a group/add form (normal entity adding).
Any ideas?
I'd use an Event Subscriber here. See My First Event Subscriber for an example if you're unfamiliar.
In this case, you'd want to subscribe to the Symfony\Component\HttpKernel\KernelEvents::REQUEST event. For example, you might have a getSubstribedEvents() method that looks like:
public static function getSubscribedEvents() {
  // Include Symfony\Component\HttpKernel\KernelEvents with a use statement.
  return [
    KernelEvents::REQUEST =&gt; 'myCustomMethod',
  ];
}

Then define myCustomMethod() to check for your session variables and redirect if needed. For example:
public function MyCustomMethod(GetResponseEvent $event) {
  $route_name = $event-&gt;getRequest()-&gt;attributes-&gt;get('_route');
  // I'm not sure what the route name is here. (You also don't need
  // to check against a route name, thought it's probably a good idea.)
  if ($route_name == 'GROUP_ADD_ROUTE') {
    // Check whatever to see if you must redirect.
    if (myRedirectCondition()) {
      // Set these response headers so browsers don't cache the redirect.
      $response_headers = [
        'Cache-Control' =&gt; 'no-cache, no-store, must-revalidate',
      ];

      // Build your response.
      $response = new TrustedRedirectResponse(MY_REDIRECT_URL, '302', $response_headers);
      // You'll have to determine how your redirect should be cached and add
      // appropriate cache dependencies, tags, contexts, etc. There is a
      // session cache context, but I'm not familiar with that particulars of
      // exactly how it works. Alternatively, you could use \Drupal::service('page_cache_kill_switch')-&gt;trigger();
      // inside your route_name if statement. 
      $response-&gt;addCacheableDependency();
      $event-&gt;setResponse($response);
    }
  }
}

Related: Disabling Page Cache for Redirect Response