Reputation: 7413
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?
Upvotes: 7
Views: 3946
Reputation: 450
This is new Symfony 2 bundle which converts form type constraints to JavaScript validation rulers https://github.com/formapro/JsFormValidatorBundle
Upvotes: 1
Reputation: 4841
Check the corresponding open issue "[Form] JavaScript validation" which contains a reference to SimpleThingsFormExtraBundle (or rather a specific, open PR of that bundle) that does that.
Upvotes: 2
Reputation: 3419
You can do something simplier:
The FieldType already passes a attr attribute to the form which is directly passed as attr var to view. You had better to modify this attr form's attribute in order to add your data-validation-constraints attribute because it will avoid you to be required to also customize the form theme to handle your new var.
<?php
namespace MyBundle\Form\Type;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormBuilder;
class FieldTypeJsValidationExtension extends AbstractTypeExtension
{
public function buildForm(FormBuilder $builder, array $options)
{
$attr = $builder->getAttribute('attr');
$attr = array_merge(
array(
'data-validation-constraints' => $this->aMethodThatRenderTheFinalContentOfTheValidationAttribute(),
),
$builder->getAttribute('attr')
);
$builder->setAttribute('attr', $attr);
}
public function getExtendedType()
{
return 'field';
}
}
Upvotes: 0