Magento 2: Adding a form key for your form

Trying to figure out how to add a form key to your form?

Posted on April 10, 2018 in Magento2

Trying to figure out how to add a form key to your form? You’ll need to add Magento\Framework\Data\Form\FormKey class as a dependency to your Block, and get the form key from the method getFormKey().

Here’s a practical example:


<?php
namespace Namespace\Module\Block;

use \Magento\Framework\View\Element\Template;
use \Magento\Framework\View\Element\Template\Context;
use \Magento\Framework\Data\Form\FormKey;

class MyBlock extends Template {

    protected $formKey;

    public function __construct(FormKey $formKey, Context $context, array $data = []) 
    {
        $this->formKey = $forKey
        parent::__construct($context, $data);
    }

    public function getFormKey()
    {
         return $this->formKey->getFormKey();
    }

}

Then in your template you can call getFormKey() method of block

<?php /** @var $block \Namespace\Module\Block\MyBlock */ ?>
<form action="/myform" method="post">
    <input type="hidden" name="form_key" value="<?php echo $block->getFormKey() ?>" />
    <!-- ... Rest of your form ... -->
</form>


comments powered by Disqus