Reputation: 1648
Background: I'm using Symfony Forms and Symfony Validation components to render a form in my applications registration page in my Silex application.
I have the form working correctly, rendering, client side validation and binding data to my entities. I've added a validation method to the entity which correctly validates the entity and produces the expected errors.
Question: I now want to get the errors out of the returned ConstraintValidationList and back into the form to display them on the front end using the twig {{ form_errors }} view helper.
I've consulted the API docs at: http://api.symfony.com/2.0/Symfony/Component/Form/Form.html and can't see the correct method for doing this. Does anyone know how to achieve what I'm looking for?
Here is the code from my Silex controller closure:
$app->post('/register-handler', function(Request $request) use($app)
{
// Empty domain object
$user = new MppInt\Entity\User();
// Create the form, passing in a new form object and the empty domain object
$form = $app['form.factory']->create(new MppInt\Form\Type\RegisterType(), $user);
// Bind the request data to the form which puts it into the underlying domain object
$form->bindRequest($request);
// Validate the domain object using a set of validators.
// $violations is a ConstraintValidationList
$violations = $app['validator']->validate($user);
// Missing step - How do I get a ConstraintValidationList back into the
// form to render the errors in the twig template using the {{ form_errors() }}
// Helper.
});
Upvotes: 2
Views: 1105
Reputation: 220
At the bind request stage validators should be run on the data so you shouldn't need to use the validation service yourself. (Coming from Sf2 rather than Silex the validator service is associated with Form I don't know if you have to do this manually for Silex)
Unless error bubbling is enabled on each field the errors will be held in the fields (children) of the form for displaying errors using {{ form_errors() }}
Although if you really need to get a constraintViolationList into a form errors, you can convert them into Symfony\Component\Form\FormError objects and add them to the form with $form->addError(FormError $formError);
Upvotes: 2