I followed this tutorial to add a captcha to my form.
First I install it using
composer require captcha-com/symfony-captcha-bundle:"4.*"
After I Install it, I got an error on a file called captcha.html.twig
Error:
captcha Unexpected "spaceless" tag (expecting closing tag for the"block" tag defined near line 2).
So I changed {% spaceless %}
to {% apply spaceless %}
And the error is gone.
But My captcha bot always returns True (even when I don't even fill it.Here is the ->add()
function of my form:
->add('captchaCode', CaptchaType::class, ['captchaConfig' => 'ExampleCaptchaUserRegistration','constraints' => [ new ValidCaptcha(['message' => 'Invalid captcha, please try again', ]), ],]);
Code of Routes.yaml :
captcha_routing: resource: "@CaptchaBundle/Resources/config/routing.yml"
Code of captcha.php :
<?php // app/config/packages/captcha.phpif (!class_exists('CaptchaConfiguration')) { return; }// BotDetect PHP Captcha configuration optionsreturn [ // Captcha configuration for example form'ExampleCaptchaUserRegistration' => ['UserInputID' => 'captchaCode','ImageWidth' => 250,'ImageHeight' => 50, ],];
Captcha field on the User.php
entity:
protected $captchaCode;public function getCaptchaCode(){ return $this->captchaCode;}public function setCaptchaCode($captchaCode){ $this->captchaCode = $captchaCode;}
Code in the View (twig)
<span class="txt1 p-b-11"> Are You a Robot?</span><div class="wrap-input100 m-b-36"> {{ form_widget(form.captchaCode, {'attr': {'class': 'input100'} }) }} <span class="focus-input100"></span></div><div class="error">{{ form_errors(form.captchaCode) }} </div>
Controlleur function:
/** * @Route("/register", name="user_register", methods={"GET","POST"}) */public function register(Request $request,UserPasswordEncoderInterface $encoder): Response{ $user = new User(); $form = $this->createForm(UserType::class, $user, ['validation_groups' => ['register'], ]); $form ->remove("description"); $form ->remove("phone"); $form ->remove("website"); $form ->remove("facebook"); $form ->remove("picture"); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $hash = $encoder->encodePassword($user,$user->getPassword()); $user->setPassword($hash); // defaults values (user can edit them later) $user->setDescription("Apparently, this User prefers to keep an air of mystery about them."); $user->setPhone(null); $user->setPicture("default.png"); $user->setWebsite(null); $user->setFacebook(null); $user->setRoles(["ROLE_USER"]); // end default values $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($user); $entityManager->flush(); return $this->redirectToRoute('user_login');} return $this->render('authentication/register.html.twig', ['user' => $user,'form' => $form->createView(), ]);}