6

我正在尝试将 EWZRecaptcha 添加到我的注册表单中。我的注册表单生成器如下所示:

public function buildForm(FormBuilder $builder, array $options)
{
    $builder->add('username',  'text')
            ->add('password')
            ->add('recaptcha', 'ewz_recaptcha', array('property_path' => false));
}

public function getDefaultOptions(array $options)
{
    return array(
            'data_class' => 'Acme\MyBundle\Entity\User',
    );
}

现在,如何将 Recaptcha 约束添加到验证码字段?我尝试将此添加到validation.yml:

namespaces:
  RecaptchaBundle: EWZ\Bundle\RecaptchaBundle\Validator\Constraints\

Acme\MyBundle\Entity\User:
  ...
  recaptcha:
    - "RecaptchaBundle:True": ~

但我得到Property recaptcha does not exists in class Acme\MyBundle\Entity\User错误。

如果我array('property_path' => false)从 recaptcha 字段的选项中删除,我会收到错误消息:

Neither property "recaptcha" nor method "getRecaptcha()" nor method "isRecaptcha()"
exists in class "Acme\MyBundle\Entity\User"

知道如何解决吗?:)

4

1 回答 1

4

Acme\MyBundle\Entity\User没有recaptcha属性,因此您在尝试验证User实体上的该属性时收到错误。设置'property_path' => false是正确的,因为这告诉Form对象它不应该尝试为域对象获取/设置此属性。

那么如何验证此表单上的该字段并仍然保留您的User实体?很简单——它甚至在文档中都有解释。您需要自己设置约束并将其传递给FormBuilder. 这是您最终应该得到的结果:

<?php

use Symfony\Component\Validator\Constraints\Collection;
use EWZ\Bundle\RecaptchaBundle\Validator\Constraints\True as Recaptcha;

...

    public function getDefaultOptions(array $options)
    {
        $collectionConstraint = new Collection(array(
            'recaptcha' => new Recaptcha(),
        ));

        return array(
            'data_class' => 'Acme\MyBundle\Entity\User',
            'validation_constraint' => $collectionConstraint,
        );
    }

关于这个方法,我不知道的一件事是这个约束集合是否会与你的合并validation.yml或者它是否会覆盖它。

您应该阅读这篇文章,它更深入地解释了设置表单并验证实体和其他属性的正确过程。它特定于 MongoDB,但适用于任何 Doctrine 实体。在本文之后,只需将其termsAccepted字段替换为您的recaptcha字段。

于 2012-01-26T20:56:49.423 回答