0

How can I change view data after failed validation (I want to change a checkbox value while displaying validation errors to explain why you can't select it). I suppose form events doesn't help here as the validation happens in the end.

2
  • Could you add some code? Commented Jul 22, 2015 at 7:29
  • There's nothing really to add.. I just have no idea how to do it. Commented Jul 22, 2015 at 7:34

2 Answers 2

1

The following code snippet from the Symfony's from bootstrap layout shows how you can check whether form field is valid or not:

{% block form_row -%}
{% spaceless %}
    <div class="form-group{% if (not compound or force_error|default(false)) and not valid %} has-error{% endif %}">
        {{ form_label(form) }}
        <div class="{{ block('form_group_class') }}">
            {{ form_widget(form) }}
            {{ form_errors(form) }}
        </div>
    </div>
{% endspaceless %}
{%- endblock form_row %}

Look at if (not compound or force_error|default(false)) and not valid you can use same check in your code.

Sign up to request clarification or add additional context in comments.

Comments

0

In short, you should add boolean value to your model, add checkbox type to your FormType representing this value and set it to false when validation fails, like this:

$form->setData($model);
if (!$form->isValid()) {
    $model->setFlag(false);
} else {
    // save model, redirect etc
}

3 Comments

Didn't work - I think this is because the data has already been bound to the form. I tried calling setData and that only threw exception "You cannot change the data of a bound form".
Try to set it to false before you call submit (of course only in case you are redirecting user if the form is valid)
The other way is to create a new instance of a form with proper data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.