I am having a problem with the Zend Framework 2 formElement csrf.
It works fine until I submit an invalid form, hit the same page then refresh the page. A "notTheSame" validation error occurs on the field and the message "The form submitted did not originate from the expected site" appears. And that is correct, because if I check the value of the csrf field, it is different from the one before submission.
The form was working fine before I decided to add the csrf field.
I am creating my csrf field as follow:
class SignupForm extends Form
{
public function __construct()
{
parent::__construct('signup');
$this->setAttribute('method', 'post')
->setHydrator(new ClassMethodsHydrator(false))
->setInputFilter(new InputFilter());
$this->add(array(
'type' => 'Zend\Form\Element\Csrf',
'name' => 'csrf',
'options' => array(
)
));
// I also add a couple of fieldsets after this
And in the view file :
<?php
$form = $this->form;
$form->setAttribute('action', $this->url('needfunding', array('action' => 'register')));
$form->setAttribute('class', "signup-form start");
$form->prepare();
echo $this->form()->openTag($form);
$applicant = $form->get('applicant');
?>
<?php $this->FormErrors($form); ?>
<?php echo $this->formRow($form->get('csrf')); ?>
(FormErrors is a view helper that retrieves the form messages and styles them)
In my controller :
public function signupAction()
{
$form = new SignupForm();
/* some unrelated code [...] */
$request = $this->getRequest();
if ($request->isPost()) {
$category_group_id = $request->getPost()->category_group;
$selected_categories = array();
foreach ($categories as $c) {
$selected_categories[$c->getId()]=html_entity_decode($c->getName());
}
$form->get('category')->setValueOptions($selected_categories);
$form->setData($request->getPost());
if ($form->isValid()) {
/* some unrelated code [...] */
return $this->redirect()->toRoute('signupconfirmation');
}
else {
}
}
return array('form' => $form, 'categories' => $ordered_categories);
}
I guess my question is, why is my csrf regenerated once I'm back on my form page because the form wasn't valid ?
PS: I could not find my solution in this post Zend Framework 2 CSRF Protection