0
votes

In symfony/twig I have a contact page that takes name and e-mail address that can be submitted. The input is validated. The form fields are at the bottom of the page. If the form is submitted I want to redirect to the bottom part of the page where the form is and where the errors or success message is displayed. In case of succes I managed to do this in the controller with;

if ($form->isValid()) {
            .... code to send mail
            return $this->redirect($request->getUri()."#form");
        }

If the form is not valid the page is rendered like this:

        else {
            $request->getSession()->getFlashBag()->add('error', 'Message not send!');
            return $this->render('default/index.html.twig', array(
                'form' => $form->createView(),
            ));
        }

and if form is not valid it returns to the top of the page. I want to return to the bottom of the page (url/#form) where the form part is and the errors are visible so the viewer sees the message was not send because of errors. Is it possible to add an anchor in rendering the form? (And not use javascript).

1
You should look here stackoverflow.com/questions/33525293/… (try to google before)BENARD Patrick
The redirect with anchor #form works for form->isValid. But my question is how to get the anchor in rendering the page if the form is unvalid. Both suggested questions don't answer this.zef
<form action="#form" method="POST"> should solve that - To do this with symfony check hereDarkBee
According to stackoverflow.com/a/53693081/1478128 what I want is not possible. The suggestion of @candybeer to use javascript was useful. I use javascript now with an event handler on submitting the form to add an anchor in the url. This works for both cases valid and unvalid form.zef

1 Answers

0
votes

if you use redirectToUrl so you will lose the form data, so you can do this with simple jquery code:

{% if not form.vars.valid %}
    <script>
        $(document).ready(function () {
        $('html,body').animate({
            scrollTop: $('#form').offset().top
        }, 1000);
        });
    </script>
{% endif %}