• en
  • hy

Magento 2 – How to add new order attribute

In this tutorial, we are going to create a new order attribute and show it in admin grid. Let’s say we want to set “Is Important” to some orders (logic is up to you). First thing we need to do is to create a new module (you can add this functionality to existing module as well). Creating a basic module is out of scope of this tutorial.

Next we need to create a setup script for our module. Setup scripts in Magento 2 should be created in Yereone/NewOrderAttribute/Setup/InstallData.php. The content will be the following

At this moment, you should already see the column in admin grid, but the value will be empty because we have not set it yet. Order attribute value can be set from different places. One method I will show is to set it when the order is created. That will be done on sales_order_save_before event. So create new events.xml file in Yereone/NewOrderAttribute/etc/events/xml with the following content

And the actual code for this will be in Yereone\NewOrderAttribute\Observer\SetOrderAttribute.php with the following content

Now after doing a new order, you should already see the value in admin grid.
Magento 2 How to add new order attribute and show in grid

Here is the module with all files in Yereone Github Repository.

Still can’t add the order attribute?. Contact US now, we provide high quality Magento development services for our customers on both Magento 1.x and Magento 2 platforms

Please Vote Here
[Total: 6 Average: 3.3]

8 Replies to “Magento 2 – How to add new order attribute”

  1. I have followed your tutorial and when I try to install the module runing setup:upgrade comment I get an error message
    “Bachus\OrderAttribute\Setup\InstallSchema must implement \Magento\Framework\Setup\InstallSchemaInterface”

    1. Hi. This means your setup class doesn’t implement \Magento\Framework\Setup\InstallSchemaInterface. Please check the top part of your InstallSchema file.

      1. I know that but your script have a bug I think because it implements InstallDataInterface when I change it acrording to magento prompt it gets another error whih says that class InstallSchema need to suit the InstallSchema interface. The another bug is that I can not display label in grid and the filters disaperad. Aslo ModuleDir/view/adminhtml/uiComponent/sales_order_grid.xml is incorrect. It schould be ui_component insted uiComponent. The observer works fine and I can see the value in grid.

    1. Hi. Use $eavSetup->addAttribute() function for each attribute to create the attributes in the database, and also for each attribute in the xml file to show them in backend form.

Leave a Reply

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

Still can’t add the order attribute?. Contact US now.!