How to get form key in Magento 2?

Member

by deron , in category: PHP CMS , 2 years ago

How to get form key in Magento 2?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by ryan.murray , a year 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.

by giovanny.lueilwitz , 7 months ago

@deron 

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

  1. Inject the MagentoFrameworkDataFormFormKey class in the constructor of your class:
1
2
3
4
5
6
7
8
9
protected $formKey;

public function __construct(
    ...
    MagentoFrameworkDataFormFormKey $formKey
) {
    ...
    $this->formKey = $formKey;
}


  1. Within your class, you can now use the $formKey object to get the form key value:
1
$formKey = $this->formKey->getFormKey();


The $formKey variable will contain the value of the form key that you can use in your form as a hidden field or wherever it's required.