0
votes

Im trying to secure my Zend form with crsf token. Allways if I add token element to my form, it always send me back notEmpty error message for token. Im I doing something wrong? Thx

class Application_Form_Test3 extends Zend_Form {

    public function init() {
        $this->setMethod('post');

//..some elements

        $note = new Zend_Form_Element_Textarea('note');
        $note->addValidator('stringLength', false, array(2, 50));
        $note->setRequired(true);
        $note->class = 'form-control';
        $note->setLabel('Poznámka:');
        $note->setAttrib('placeholder', 'poznamka ke spisu');
        $note->setOptions(array('cols' => '20', 'rows' => '4'));

        $submit = new Zend_Form_Element_Submit('submit');
        $submit->class = 'btn btn-success';
        $submit->setValue('odeslat');

        $this->addElements(array(
            $number,
            $year,
            $owner,
            $note,
            $submit,
        ));

        $this->addElement('hash', 'no_csrf_foo', array('salt' => 'unique'));
    }

}

Action in controller:

public function findAction() {
    $request = $this->getRequest();
    $form = new Application_Form_Test3();

    if ($this->getRequest()->isPost()) {
        if ($form->isValid($request->getPost())) {
            var_dump($request->getPost());
        } else {
            var_dump("ERROR");
        }
    }

    $this->view->form = $form;
}

In my view I render form and dump error messages

...
<?php echo $form->renderForm(false); ?>
...
//render single elements here
//eg.  <?php echo $form->note->renderViewHelper(); ?>
...
    <?php var_dump($form->getMessages()) ?>
...

After each validation of form, i get array of error messages like that:

array(2) { ["note"]=> array(1) { ["isEmpty"]=> string(36) "Value is required and can't be empty" }  ["no_csrf_foo"]=> array(1) { ["isEmpty"]=> string(36) "Value is required and can't be empty" } } 

if I fill good values to elements, the last one error is always for token - NotEmpty, so my form is never valid.

1
How is the CSRF element displayed in the form? Can you edit the question and add the HTML output of the CSRF token?Benz
Yes, problem was that I didnt render token element. I dont use decorators in my form, so I render every single element in view manually, so i forgot to render csrf token. So thx for your comment, which gave me solution.porosman
Nice find :). If you answer your own question you can set is as 'solved' should take care of any other incoming users to answer this question :)Benz

1 Answers

0
votes

Problem solved. I didnt render token element in my View so i added to View:

<?php echo $form->no_csrf_foo->renderViewHelper(); ?>