Symfony2将reCaptcha字段添加到注册表单

tam*_*mir 6 forms recaptcha symfony symfony-2.0

我正在尝试将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',
    );
}
Run Code Online (Sandbox Code Playgroud)

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

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

Acme\MyBundle\Entity\User:
  ...
  recaptcha:
    - "RecaptchaBundle:True": ~
Run Code Online (Sandbox Code Playgroud)

但我得到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"
Run Code Online (Sandbox Code Playgroud)

知道怎么解决吗?:)

lee*_*eek 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,
        );
    }
Run Code Online (Sandbox Code Playgroud)

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

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

  • 从 Symfony 2.1 开始,应该使用 `mapped=false` 而不是 `property_path=false`,请参阅 http://symfony.com/doc/current/reference/forms/types/form.html#property-path 和 http://symfony.com/doc/current/reference/forms/types/form.html#property-path 和 http://分别为/symfony.com/doc/current/reference/forms/types/form.html#mapped。 (2认同)