How to create custom order attribute , save and show in admin grid in magento 2?

How to create custom order attribute, save and show in admin grid in magento 2? – Today i am going to write about creating custom order attributes. And save data to the created attribute and show that attribute in the admin grid.

To easy their business process our clients wants to add extra information to their process.To achieve this we are creating customer attributes, product attributes and order attributes accordingly. So here let’s see how to create custom order attributes.

To create the custom order attributes we need to follow below steps.

  1. Create a basic custom module.
  2. Create an UpgradeData file under setup directory.
  3. Save the order attribute using observer.
  4. Syncing the sales_order table and sales_order_grid table.
  5. Show order attribute in grid.

Entire module structure

magento 2 order attributes
Module Structure.

Create a basic custom module.

Only module.xml file below and rest of the stuffs in creating a module is pretty common.

Create an UpgradeData file under setup directory.

Here we are just creating the custom order attribute. The attribute code is dropship_available . With this upgrade data this field is created in the sales_order table and sales_order_grid table. To create in the sales_order_grid table we are using ‘grid’ => true.

Save the order attribute using observer.

After creating the attribute we want to save the value for this attribute. Here i am approaching the event and observer method. Here i am using sales_order_save_after event to update the order attribute. For this we want to add the events.xml , observer files respectively.

Next see the observer file.

In this observer i am setting some values to custom order attribute and save the order object. Readers can go with what ever the logic they need here. With this part now when after placing the order custom order attribute too saved the value.

Syncing the sales_order table and sales_order_grid table.

For this we want to update the di.xml file under etc directory with below content.

Show created order attribute in grid.

To show this update the content for sales_order_grid.xml

Now after placing order you can see the order grid like below.

custom order attribute in magento 2
Admin order grid with custom order attribute

That’s it for today. Have a nice day.Enjoy coding , Learn , Experience , Teach and Help.

Praying for the quick recovery from Covid19. RIP those who are lost their lives because of this dangerous Covid19.

Leave a Reply

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