Symfony2 add reCaptcha field to registration form

2019-03-28 03:04发布

问题:

I'm trying to add EWZRecaptcha to my registration form. My registration form builder looks something like this:

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',
    );
}

Now, how can I add the Recaptcha Constraint to the captcha field? I tried to add this to validation.yml:

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

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

But I get Property recaptcha does not exists in class Acme\MyBundle\Entity\User error.

If I remove array('property_path' => false) from the recaptcha field's options, I get the error:

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

Any idea how to solve it? :)

回答1:

Acme\MyBundle\Entity\User does not have a recaptcha property, so you're receiving errors for trying to validate that property on the User entity. Setting 'property_path' => false is correct, as this tells the Form object that it shouldn't try to get/set this property for the domain object.

So how can you validate that field on this form and still persist your User entity? Simple - it is even explained in the documentation. You'll need to setup the constraint yourself and pass it to the FormBuilder. Here is what you should end up with:

<?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,
        );
    }

The one thing I don't know about this method, is whether this constraint collection will be merged with your validation.yml or if it will overwrite it.

You should read this article which explains a bit more in-depth the proper process for setting up forms with validation for entities and other properties. It is specific to MongoDB but applies to any Doctrine entity. Following this article, just replace its termsAccepted field with your recaptcha field.