我关注了this tutorial,将验证码添加到了表单中。
首先我使用
安装它composer require captcha-com/symfony-captcha-bundle:"4.*"
安装后,我在名为captcha.html.twig
的文件上出错
错误:
captcha意外的“无空格”标记(预期 在第2行附近定义的“ block”标记。
所以我将{% spaceless %}
更改为{% apply spaceless %}
错误消失了。
但是我的验证码机器人始终返回True(即使我什至没有填写)。
这是我的表单中的->add()
函数:
->add('captchaCode', CaptchaType::class, [
'captchaConfig' => 'ExampleCaptchaUserRegistration',
'constraints' => [
new ValidCaptcha([
'message' => 'Invalid captcha, please try again',
]),
],]);
Routes.yaml代码:
captcha_routing:
resource: "@CaptchaBundle/Resources/config/routing.yml"
captcha.php代码:
<?php
// app/config/packages/captcha.php
if (!class_exists('CaptchaConfiguration')) { return; }
// BotDetect PHP Captcha configuration options
return [
// Captcha configuration for example form
'ExampleCaptchaUserRegistration' => [
'UserInputID' => 'captchaCode',
'ImageWidth' => 250,
'ImageHeight' => 50,
],
];
User.php
实体上的验证码字段:
protected $captchaCode;
public function getCaptchaCode()
{
return $this->captchaCode;
}
public function setCaptchaCode($captchaCode)
{
$this->captchaCode = $captchaCode;
}
视图中的代码(树枝)
<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函数:
/**
* @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(),
]);
}