How to add form key in Magento 2?
How to add form key in Magento 2?

How to add form key in Magento 2?

In this article, I will show you how you can use form key in your form in phtml file.

In Magento, form key is used for preventing Cross-Site Request Forgery. Learn more about cross-site forgery

You can use directly getBlockHtml('formkey') to get form key with a hidden field in phtml files like

echo $block->getBlockHtml('formkey');

OutPut:

<input name=”form_key” type=”hidden” value=”XDC59C3w7X8GrKYM”>

 <input name="form_key" type="hidden" value="XDC59C3w7X8GrKYM">

We can also get form key by Magento\Framework\Data\Form\FormKey class from the method getFormKey().

With Object Manager:

<?php 
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$FormKey = $objectManager->get('Magento\Framework\Data\Form\FormKey'); 
?>

Now you can get form key in phtml file like

<!--Hidden form key field after <form> tag-->
<input name="form_key" type="hidden" value="<?php echo $FormKey->getFormKey();?>">

With Dependency Injection:

protected $formKey;

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

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

Now you can get form key in phtml file like

<form>
<input name="form_key" type="hidden" value="<?php echo $block->getFormKey();?>">
...
...
</form>

NOTE: ObjectManage is not a recommended way. Read more  ObjectManager – Magento 2 Developer Documentation

I hope this will help you to understand how to get a form key in Magento 2. If you have any query feel free to comment below.

Please share this post and Follow me on social media via the following links to get updated with the latest post of Magento. Happy Coding…:)