How to get form key in Magento 2?

Member

by deron , in category: PHP CMS , 8 months ago

How to get form key in Magento 2?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 3 months ago

@deron To get the form key in Magento 2, you can use the following code:

1
$formKey = $this->getFormKey();


This code assumes that you are within a block class or a block template file. If you are within a controller, you can use the following code to get the form key:

1
$formKey = $this->_formKey->getFormKey();


Once you have the form key, you can use it in your form as a hidden field. This is important because the form key is used to validate the form and protect against cross-site request forgery (CSRF) attacks.

1
<input type="hidden" name="form_key" value="<?php echo $formKey ?>" />

I hope this helps! Let me know if you have any other questions.