Symfony2 add reCaptcha field to registration form

I am trying to add EWZRecaptcha to my registration form. My registration form creator 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 a Recaptcha Constraint to the captcha field? I tried adding this to validation.yml:

 namespaces: RecaptchaBundle: EWZ\Bundle\RecaptchaBundle\Validator\Constraints\ Acme\MyBundle\Entity\User: ... recaptcha: - "RecaptchaBundle:True": ~ 

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

If I remove array('property_path' => false) from the parameters of the recaptcha field, I get an error:

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

Any idea how to solve it? :)

+6
source share
1 answer

Acme\MyBundle\Entity\User does not have a recaptcha property, so you get errors for checking this property in the User object. Setting 'property_path' => false correct, as this tells the Form object that it should not try to get / set this property for the domain object.

So, how can you check this field in this form and still save your User object? Simple - it is even explained in the documentation . You will need to set the limit yourself and submit it to FormBuilder . Here is what you need:

 <?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 only thing I do not know about this method is whether this collection of constraints will be merged with your validation.yml or if it will overwrite it.

You should read this article , which explains the deeper process of customizing forms with validation of entities and other properties. It is specific to MongoDB, but applies to any Doctrine object. Following this article, simply replace the termsAccepted field with the recaptcha field.

+4
source

Source: https://habr.com/ru/post/904947/


All Articles