5
if (!$this->_validateFormKey()) {
  // do something
}

Any Magento 1 equivalent in Mangento 2 for _validateFormKey function.

And Can anyone explain how and where Magento checks formkey, when any form is submitted.

Basically I am not able to validate the formkey in controller, My form is submitted even if change the formkey value from inspect element.

4 Answers 4

19

Try following way:


protected $formKeyValidator;

public function __construct (
    \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator
) {
    $this->formKeyValidator = $formKeyValidator;
}

And then


if (!$this->formKeyValidator->validate($this->getRequest())) {
    // invalid request
}
1
  • It's not working in Chrome but working properly in firefox.
    – Magecode
    Feb 16, 2018 at 4:57
2

There is also in Magento 2 a form key validator

Magento\Framework\Data\Form\FormKey\Validator

Have a look on the customer loginPost controller to see an example of its use

vendor/magento/module-customer/Controller/Account/LoginPost.php
0

Add formkey inside the form like below and follow the above steps for validating in controller.

<?= $block->getBlockHtml('formkey') ?>
0

Some previous answer is correct but I am elaborate it.

namespace Equaltrue\Themeoption\Controller\Taxmode;

class Index extends \Magento\Framework\App\Action\Action
{

    /**
     * @var Validator
     */
    protected $formKeyValidator;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param Validator $formKeyValidator
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
            \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator
    )
    {
        $this->formKeyValidator = $formKeyValidator;
        parent::__construct($context);
    }

    public function execute()
    {
        if ($this->formKeyValidator->validate($this->getRequest())) {
            // form key is validate
        }
    }
}

Now you may face a problem if you use localhost in user like URL: http://localhost/magento2/

The Form Key from website & Magento will not match. You can check it from following Magento core file.

vendor/magento/framework/Data/Form/FormKey/Validator.php

Now you have to change localhost to 127.0.0.1 or your IP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.