Search code examples
zend-framework2zend-formcsrf

How to generate a new Csrf-Token for a Form


i got a Form. When i change a Select-Element inside that Form, i do an Ajax-Call to the same URL, which basically loads a new Form that has some additional Fields or has some Fields removed (different Categories, different Fields...).

Now, the Form i get from the Request obviously will have the SAME Csrf-Token, since the Token lives for one Request. Meaning, i will have to generate a new token, whenever i do this kind of action, but i have seriously no idea on how to do this.

My assumption is that i have to do something like

if ($request->isXmlHttpRequest()) {
    $form->get('csrf')    ->regenerateCsrfToken()
}

But obviously that function doesn't exist, but it should be something alike those lines. Any input will be greatly appreciated


Solution

  • Have you tried this:

    if ($request->isXmlHttpRequest()) {
        $form->get('csrf')->getCsrfValidator()->getHash(true);
    }
    

    getHash(true) will regenerate the hash, and store the changed hash in the generator, so your form will retrieve the new value when you retrieve it from the element later.