I render a form from the following controller method:
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')
])
}
The form I render is 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>
The form will be submited via Ajax (I do not place javascript code in order to keep the question as small as possible) using a seperate controller method. For example:
public function submitFormAction(Request $request)
{
// Implement sumbit code here
}
What I want to test first via a phpunit functional test is the normal behavior of ajax Submission but how I will get: * The current csrf token * Captha string
WITHOUT needing to render completely the page where the csrf token and captcha is placed (because it is part of a multiple form).
For captcha I use gregwar's implementation and I define it as a service via:
app.captcha:
class: 'Gregwar\Captcha\CaptchaBuilder'
public: true
(I do not use the Bundle because I find it incovenient in my case where I use Ajax. I plan to make my own Service in a immediate refactor.)