Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Adding CSRF validation to forms when extending Phalcon\Form

Is it possible to make \Phalcon\Security available to \Phalcon\Form so as to aid in the generation of csrf hidden fields when extending the class.

class Login extends \Phalcon\Form
{
    public function initialize()
    {
        // Identity Field.
        $identity = new Text('identity');
        $identity->addValidator(new Email(
            array(
                'message' => 'A valid email address is required.'
            )
        ));
        $identity->setLabel("Email Address.");
        $this->add($identity);

        // Password Field.
        $password = new Password('passowrd');
        $password->setLabel('Password');
        $password->addValidator(new PresenceOf(
                array(
                    'message' => 'You must provide a password.'
                )
            ));
        $this->add($password);

        $csrf = new Hidden(array(
            'name' => $this->security->getTokenKey(),
            'value' => $this->security->getToken(),
            'id' => 'xtoken'
        ));

       $csrf->addValidator(new Csrfl(
            array(
                'message' => 'Tokens do not match.'
            )
        ));
        $this->add($csrf);
    }
}


81.2k
Accepted
answer

Hi, you can access the DI statically:

$di = Phalcon\DI::getDefault();

$security = $di['security'];


8.8k

Ya that will work nicely, thanks.