如何为在表单生成器(Symfony2)中创建的表单启用验证



>我使用表单构建器创建和呈现我的表单,但似乎验证被禁用或无法正常工作。我将验证规则保存在 validation.yml 文件中。方法$form->isValid()始终返回 true ,并且$form->getErrorsAsString()不显示任何错误(仅[FieldName1]: No errors, [FieldName2]: No errors ... etc)。

我以这种方式创建表单:

$form = $this->createForm( new CategoryType(), new Category() );

然后我把它送到树枝上。

可能是什么原因?如何启用验证?

-----更新-------------------------

我以这种方式创建一个表单:

public function indexAction()
{
    return $this->render('MyBundle:MyView:index.html.twig', array(
        "form" => $this->createForm( new CategoryType(), new Category() )->createView()
    ));
}

类别类型非常简单:

class CategoryType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options) {
       $builder ->add('name', 'text')
                ->add('categoryId', 'entity', array(
                    'class' => 'MyBundle:Category',
                    'property' => 'name',
                ));
    }
    public function getName() {
        return 'my_form_name';
    }
}

当然还有验证.yml:

MyBundle/Form/Type/CategoryType:
    properties:
    - name:
        - NotBlank: ~
        - Length:
            min: 3
            max: 30
MyBundle/Entity/Category:
    properties:
    - name:
        - NotBlank: ~
        - Length:
            min: 3
            max: 30

我不知道我应该使用哪个版本,但它们都不起作用。

我认为

这个话题会对你有所帮助。

您必须检查 config.yml 中的验证器配置是否定义如下:

framework:
    validation: { enabled: true, enable_annotations: false }

最新更新