Create combined client side and server side validation in Symfony2
Posted
by
ausi
on Stack Overflow
See other posts from Stack Overflow
or by ausi
Published on 2011-11-05T22:59:07Z
Indexed on
2011/11/16
9:51 UTC
Read the original article
Hit count: 448
I think it would be very useful to create client side form validation up on the symfony2 Form
and Validator
components.
The best way to do this would be to pass the validation constraints to the form view. With that information it would be possible to make a template that renders a form field to something like this:
<div>
<label for="form_email">E-Mail</label>
<input
id="form_email" type="text" name="form[email]" value=""
data-validation-constraints='["NotBlank":{},"MinLength":{"limit":6}]'
/>
</div>
The JavaScript part then would be to find all <input>
elements that have the data-validation-constraints
attribute and create the correct validation for them.
To pass the validation constraints to the form view i thought the best way would be to create a form type extension. That's the point of my Question: Is this the correct way? And how is this possible?
At the Moment my form type extension looks like this:
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormBuilder;
class FieldTypeExtension extends \Symfony\Component\Form\AbstractTypeExtension{
public function getExtendedType(){
return 'field';
}
public function buildView(FormView $view, FormInterface $form)
{
// at this point i didn't find a way to get the
// validation constraints out of the $form
// the `getAllValidationConstraints` here is just an example
$view->set('validation_constraints', $form->getAllValidationConstraints());
}
}
How can i get all validation constraints applied to one form field out of the FormInterface object?
© Stack Overflow or respective owner