Automatic page return link in Symfony

Viewed 146

I would like to find a proper way to add a cancel close button next to the submit button on forms with Symfony 5. Based on my research on Internet, I found various ways :

  • add the button on the twig template with the submit_widget blog. It works, but I'm not able to change the route as I can't transfert any variables from the Controller.

  • add a simple like with href="javascript:history.go(-1)". Efficient but ugly !

  • add an other submit button with an formnovalidate attribute based on that post and that post. But I seems that this function is longer working in Symfony 5.

I can't figure out that this type of feature is not possible on a framework.

Thanks for your help.

2 Answers

I've finally found a solution based on the advice of emix.

So yes, obviously, let's forget the js option.

To access to a variable inside the twig form template, I simply pass a variable 'route_back' in the Controller :

$view = $form->createView();
$view->vars['route_back']='account';
return $this->render('home/index.html.twig', [
    'form' => $view
]);

And then, add dynamically insert the link in the twig form template :

{%- block form_end -%}
    <div class="row mt-5">
        <div class="col-6 text-right">
            <a class="btn-secondary btn w-75" href="{{ path(route_back) }}">{% trans %}Cancel{% endtrans %}</a>
        </div>
        <div class="col-6 text-left">
            <button type="submit" id="account_save" name="account[save]" class="btn-primary btn w-75">{% trans %}Save{% endtrans %}</button>
        </div>
    </div>
{%- endblock form_end -%}

On the type form, I've removed of course the submit button as recommended in the official documentation :

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', TextType::class)
        ->add('email', EmailType::class)
    ;
}

You are supposed to manually create the button in the Twig view and set up it's href accordingly.

Eg. if you are on the blog_posts_edit page, create a link to the block_posts_index page (mutatis mutandis):

<a href="{{ path('blog_posts_index') }}">
    Return to the list
</a>
Related