Problem 1
I'd like to build a registration form via ajax submission. Registration works is the $form->isValid()
. However, if the form fails registration I need to return these errors via ajax.
if ($form->isValid()) {
}else{
$errors = $form->getErrors();
// return some json encoded errors here
}
$form->getErrors()
returns an empty array even though the form did not validate (in this case I am testing with a username that is too short).
Problem 2
The second problem I have is that if the form validates but there is still an error. For example a unique field that someone tries to submit the same value for.
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($form->getData());
$em->flush();
// error could be a username submitted more than once, username is unique field
}else{
// ...
}
How can I catch that error and return it via json?
In your form builder you can use error_bubbling
to move the errors into your form object. When you specify the field, pass it in as an option like this:
$builder->add('username','text', array('error_bubbling'=>true));
and you can access errors in your form object like this:
$form->getErrors();
Outputs something like
array (
0 =>
Symfony\Component\Form\FormError::__set_state(array(
'messageTemplate' => 'Your username must have at least {{ limit }} characters.',
'messageParameters' =>
array (
'{{ value }}' => '1',
'{{ limit }}' => 2,
),
)),
) [] []
fyi: If you are using Form/Type's you can't set error_bubbling
as a default value, it has to be assigned to each field.
Useful link: http://symfony.com/doc/2.0/reference/forms/types/text.html#error-bubbling
http://symfony.com/doc/2.0/reference/constraints/UniqueEntity.html
The errors aren't on the form itself. Form::getErrors
would only return errors if there were any on the form object itself. You need to traverse the form and check for errors on each child.
Form::isValid
on the contrary just traverses the children and check if any of them are invalid.
If there still are "errors" after validation, that means that your validation isn't complete. If your application requires a non-standard constraint, you should just go ahead and write a custom constraint. See the cookbook entry on writing custom validator constraints for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With