Reading list Switch to dark mode

    Add Form Key in phtml Magento 2

    Updated 26 March 2024

    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.

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    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 🙂

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home