We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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);
    }
}


98.9k
Accepted
answer

Hi, you can access the DI statically:

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

$security = $di['security'];


15.2k

Ya that will work nicely, thanks.