我通过以下控制器方法呈现表单:
public function indexAction(Request $request)
{
$session=$this->get('session');
$builder = $this->get('app.captcha');
$builder->build();
$session->set('registration_step2',$builder->getPhrase());
return $this->render('pages/registration.html.twig',[
'image'=>$this->createCaptcha('registration_step2')
])
}
我呈现的表单为pages/registration.html.twig
:
<form id="contactForm" class="col-12" data-scroll-to="displayRegistationPaperApplicationWrapper" action="{{ path('registration_email_contact') }}" method="post">
<input type="hidden" name="csrf" value="{{ csrf_token('insert-email') }}"/>
<div class="col-12 mb-3">
<div class="col-12">
<div class="input-group">
<div class="input-group-prepend">
<button class="btn btn-secondary" data-autofill-to="autofill_email" data-autofill-from="registrationEmail" id="emailAutofill">{{ 'register.step2.email.autofill'|trans }}</button>
</div>
<input id="autofill_email" type="email" name="autofill_email" class="form-control" placeholder="{{ 'register.step2.email'|trans }}" required/>
</div>
</div>
</div>
<div class="col-12">
<div class="col-2 float-left border">
<img id="capthaImage" class="img-fluid" data-captha-renew="registration_step2" src="{{ image }}">
</div>
<div class="col-10 float-right">
<div class="input-group">
<div class="input-group-prepend">
<button class="btn btn-secondary" id="reset-captcha">{{ 'register.captha.new-image'|trans }}</button>
</div>
<input type="text" name="captcha" class="form-control" placeholder="{{ 'register.captcha'|trans }}" required/>
</div>
</div>
</div>
<div class="col-12 mt-5 mb-2">
<div class="col-12 col-sm-12 col-md-5 col-lg-5 ml-auto">
<div class="btn-group" role="group" aria-label="Basic example">
<button id="rejectEmail" data-scroll-to="displayRegistationPaperApplicationWrapper" type="button" class="btn btn-link text-danger">{{ 'register.step2.no'|trans }}</button>
<button type="submit" class="btn btn-success">{{ 'register.step2.yes'|trans }}</button>
</div>
</div>
</div>
</form>
将使用单独的控制器方法通过Ajax提交表单(我不放置javascript代码以使问题尽可能小)。例如:
public function submitFormAction(Request $request)
{
// Implement sumbit code here
}
我首先要通过phpunit功能测试进行测试的是ajax提交的正常行为,但是我将如何获得: *当前的csrf令牌 * Captha字符串
根本没有需要完全渲染放置csrf令牌和验证码的页面(因为它是多种形式的一部分)。
对于验证码,我使用gregwar's实现,并通过以下方式将其定义为服务:
app.captcha:
class: 'Gregwar\Captcha\CaptchaBuilder'
public: true
(我不使用Bundle,因为在使用Ajax的情况下我发现它不方便。我计划立即重构自己的Service。)