0

I send a link to a URL by email. This page is created with a controller which contains a form (FormAPI). I pass a token as a parameter to secure access to this form. So I check if this token exists and I display the form. Everything works correctly.

If the token does not exist, I would like to redirect in the buildform to a custom route. But I can not.

I tried different things like this but it doesn't seem to work in the buid form.

 public function buildForm(array $form, FormStateInterface $form_state, $token = null): array {

        $nodes = \Drupal::entityTypeManager()
            ->getStorage('node')
            ->loadByProperties([
                'field_token' => $token,
            ]);

        // Checks if the node array is not empty.
        if (!empty($nodes)) {
            $node = reset($nodes);
            $nid = $node->id();
        } else {
            // Here, I want to redirect to custom route
            dump('ko');

            //return new RedirectResponse(Url::fromRoute('my_custom_route')->toString());
            //$form_state->setRedirect('my_custom_route');

            //return $this->redirect('my_custom_route');
            // return $form_state->setRedirect('('my_custom_route')');
        }
}

Do you know how I can do it? Otherwise, rather than using a controller and a custom route, I will generate a different form depending on the condition (a form without fields but with custom markup). But I prefer a controller.

I know how to redirect in submitForm() or in a controller. Here, the redirect is in buildForm()

2 Answers 2

0

You need to use RedirectResponse, e.g.

use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

$response = new RedirectResponse(URL::fromRoute('my_custom_route')->toString());
$response->send();
3

If the form is in a route via the _form key you can return the redirect the same as in a controller, the core form controller is able to pass the response to the Drupal kernel. If the form is in a custom controller you have to pass it from the form to the controller and return it.

BTW the response send method is a low-level method not suitable for a Symfony app like Drupal. The Symfony kernel has to return a response and not send one.

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.