Symfony2 add reCaptcha field to registration form

帅比萌擦擦* 提交于 2019-12-04 06:37:10

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!