Add Form Key in phtml Magento 2
Form key in Magento are a means of preventing against Cross Site Request Forgery, i,e, it is to keep your site safe from people trying to post to your forms from other sites posing as you.
This blog is to show how to generate form key to use in phtml file.
In phtml file-
<input type="hidden" name="form_key" value="<?php echo $block->getFormKey() ?>" />
In your block file-
<?php namespace Company\Module\Block\Adminhtml\BlockFolder; class BlockPage extends \Magento\Framework\View\Element\Template { /** * @param \Magento\Backend\Block\Widget\Context $context * @param \Magento\Framework\Data\Form\FormKey $formKey * @param array $data */ public function __construct( \Magento\Backend\Block\Widget\Context $context, \Magento\Framework\Data\Form\FormKey $formKey, array $data = [] ) { parent::__construct($context, $data); $this->formKey = $formKey; } /** * get form key * * @return string */ public function getFormKey() { return $this->formKey->getFormKey(); } }
and you will get your form key in your phtml file.
Or you can use this in your phtml file directly
<?php echo $block->getBlockHtml('formkey')?>
This will result in a hidden textbox with the form key in it like this
<input type="hidden" value="7yRSvrrxnQa5B62o">
Happy coding 🙂
Categories:
Magento2
Tags:
form key
View Comments
Comment or Ask a Question
Quick Links