phpsymfonyhttp-redirect

Redirect with a form is blocked


I have a problem with redirectResponse on Symfony 7.2. It works fine with Symfony 6.4.

If I call the redirection directly, everything is OK.If the redirection is called by a form, it does not work.

Here is an example :

<?php

namespace App\Controller;

use App\Form\TestType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController extends AbstractController
{
    #[Route(path: '/redirection', name: 'redirection')]
    public function redirection(): RedirectResponse
    {

        return new RedirectResponse('https://example.com');

    }
    
    #[Route(path: '/formulaire', name: 'formulaire')]
    public function index(Request $request): RedirectResponse|Response
    {
        $form = $this->createForm(TestType::class);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            return new RedirectResponse('https://example.com');
        }

        return $this->render('test.html.twig', [
            'form' => $form,
        ]);
    }


}

// The form (a simple submit button).

<?php

namespace App\Form;


use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class TestType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('submit', SubmitType::class, [])
        ;

    }


    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
        ]);
    }
}

If I consult the "/redirection" route, the redirect happens as expected. If I consult the "/formulaire" route, it gets stuck. I have an error message "Cross-Origin Request Blocked: The "Same Origin" policy does not allow viewing the remote resource located at https://example.com/. Reason: The CORS header "Access-Control-Allow-Origin" is missing. Status code: 501."

Am I wrong somewhere? Is there a configuration missing somewhere?


Solution

  • I found a solution:

    Just modify the form call to disable data-turbo in template:

    {{ form_start(form, { 'attr': {'data-turbo': 'false'} } ) }}
    

    This time the redirection goes normally