Hackasaurus
Hackasaurus

Reputation: 73

Symfony form rendering showing errors too soon

I'm using Symfony to create a form. Between the form label and the widget where the user enters data I have a button that when pressed displays text prompts to help guide the user. This works fine and when the user clicks on the button it correctly displays the text, however it also displays the error message for the field, saying that the field cannot be blank. I don't need the error displayed until the form is submitted so it seems to be displaying it too early. Many thanks for any suggestions.

Here is the relevant part of the template:

{{ form_start(form) }}
                 
{{ form_label(form.field1, 'My Custom Task Label') }}
                   
<button onclick="myFunction()">Click to display prompts</button>

<div id="myDIV" style = "display:none">
    This is a helpful prompt.
</div>
                
{{ form_widget(form.field1) }}

<script>
    function myFunction() {
    var x = document.getElementById("myDIV");
    if (x.style.display === "none") {
        x.style.display = "block";
        } else {
        x.style.display = "none";
        }
    }
</script>
                
{{ form_end(form) }}

Upvotes: 0

Views: 159

Answers (1)

Jakumi
Jakumi

Reputation: 8374

buttons by default are submit buttons. your button doesn't indicate any type, so it's of submit type. solution: set type to "button":

<button type="button" onclick="myFunction()">Click to display prompts</button>

otherwise it's sending the form / trying to send the form, obviously catching the errors / required fields, hence displaying an error.

Upvotes: 1

Related Questions