Adding an Export button to the Sales Order Grid in Magento 2 allows you to easily export order data to a text file.

In this article, we will explore how to accomplish this task and avoid the form key issue.

<exportButton>
	<settings>
		<options>
			<option name="txt" xsi:type="array">
				<item name="value" xsi:type="string">txt</item>
				<item name="label" xsi:type="string" translate="true">TXT</item>
				<item name="url" xsi:type="string">Vendor_Module/index/index/key/_current/form_key/#{form_key}</item>
			</option>
		</options>
	</settings>
</exportButton>

This code snippet represents the export button configuration in the sales_order_grid.xml file.

The "exportButton" node defines the button, and within the "settings" node, we have the "options" node, which provides the export format options.

To make sure there is no form key error you need to modify the URL value in the "options" node:


## <item name="url" xsi:type="string">Vendor_Module/index/index/key/_current/form_key/#{form_key}</item>

The "_current" placeholder will automatically generate the form key for the current session, and the "#{form_key}" placeholder will insert the form key into the URL.

With this modification, the form key will be included in the export request, and the form key error will be resolved.

Additionally, make sure that the export action is defined in the controller at the specified URL path.

In the corresponding controller action, you can retrieve the form key using the Magento\Framework\Data\Form\FormKey class, and process the export logic to generate the text file.