我认为在symfony2 Form和Validator组件上创建客户端表单验证非常有用.
执行此操作的最佳方法是将验证约束传递给表单视图.
有了这些信息,就可以制作一个模板,将表单字段呈现为:
- <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>
然后JavaScript部分将找到所有< input>具有data-validation-constraints属性的元素,并为它们创建正确的验证.
要将验证约束传递给表单视图,我认为最好的方法是创建表单类型扩展.这就是我的问题:这是正确的方法吗?这怎么可能?
在片刻,我的表单类型扩展如下所示:
- 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());
- }
- }
如何从FormInterface对象中获取应用于一个表单字段的所有验证约束?
检查相应的打开问题
“[Form] JavaScript validation”,其中包含对SimpleThingsFormExtraBundle的引用(或者更确切地说是该包的特定,打开的PR).