atwix

Adding a custom attribute/column to the orders grid in Magento admin

Does your Magento order grid have all of the fields you need? Adding or removing columns is fairly simple. Let’s explore how.
Here we will discuss both:
- Adding a custom attribute/column to the order grid.
- Removing a column that you don’t need.

The grid is under Sales -> Orders.

We are going to first copy the core file to a local directory, then code a bit.
Copy /app/code/core/Mage/Adminhtml/Block/Sales/Order/Grid.php to /app/code/local/Mage/Adminhtml/Block/Sales/Order/Grid.php. First, to make custom attribute available for inserting to grid we need to modify _prepareCollection function.
Here, we are working with database table fields and using SQL joins. Let`s suppose that we need to add a postcode column. Search for _prepareCollection function and simply add this line:

$collection->getSelect()->join('sales_flat_order_address', 'main_table.entity_id = sales_flat_order_address.parent_id',array('postcode'));

before

return parent::_prepareCollection();

so function will look like:

protected function _prepareCollection()
    {
        $collection = Mage::getResourceModel($this->_getCollectionClass());
        $collection->getSelect()->join('sales_flat_order_address', 'main_table.entity_id = sales_flat_order_address.parent_id',array('postcode'));
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

As you can see, we have joined the sales_flat_order_address table that stores the postcode field. To insert this column into the order grid, edit _prepareColumns() function. Here you can see how default columns are inserted, so using the addColumn method, we add our own postcode column.

$this->addColumn('postcode', array(
            'header' => Mage::helper('sales')->__('Postcode'),
            'index' => 'postcode',
        ));

That’s it.
Magento orders grid - custom column
Similarly, for removing a field, you just need to delete the corresponding portion of code.
A few more advanced examples are provided below.

Making a new custom Address column that consists of country, city and street:

$collection->getSelect()->join('sales_flat_order_address', 'main_table.entity_id = sales_flat_order_address.parent_id',array('telephone','postcode','address'=>new Zend_Db_Expr('concat(sales_flat_order_address.country_id, ", ",sales_flat_order_address.city, ", ",sales_flat_order_address.street)')) );

Product SKUs of an order:

$collection->getSelect()->join('sales_flat_order_item', '`sales_flat_order_item`.order_id=`main_table`.entity_id', array('skus'  => new Zend_Db_Expr('group_concat(`sales_flat_order_item`.sku SEPARATOR ", ")')));

The last, is an example of adding custom product attributes. It stores at catalog_product_entity_varchar table and we need to know its attribute_id:

$collection->getSelect()->join('sales_flat_order_item', '`sales_flat_order_item`.order_id=`main_table`.entity_id AND `sales_flat_order_item`.parent_item_id IS NULL  ', null);
$collection->getSelect()->join('catalog_product_entity_varchar', '`catalog_product_entity_varchar`.attribute_id=144 AND `catalog_product_entity_varchar`.entity_id = `sales_flat_order_item`.`product_id`', array('models'  => new Zend_Db_Expr('group_concat(`catalog_product_entity_varchar`.value SEPARATOR ",")')));

Remember to look at the database and see which tables store the necessary attributes.
I hope this article was helpful for you!
Update. It is recommended to avoid rewriting and overring core classes. Take a look at two our articles that describe better way of adding columns to Magento admin grids: Adding a column to Magento orders grid – alternative way using layout handles and Adding a column to the customers grid in Magento admin. Alternative way.


  • None

    Thank you, very helpfull.

  • Vipin Sahu

    Thanks for the article how can we show product thumbnails in magento sales order grid ?

  • Omar Farooq

    Hello i need to add column category name in items list grid (order detail page magento admin) also need to make columns sortable can some one guide me how can i do that please see image

    thanks

    http://i.stack.imgur.com/Ns2uJ.png

    • Anonymous

      hi, you can edit template phtml file and add some JavaScript for sorting this table columns.

  • Anonymous

    This technique does mean that if you are using 1.6 you’ll get a fatal error if you try and use the filtering on the newly added column.

  • srikanth thandra

    Hi,

    Thanks for the code it works great. I want to have country in the list but in the table its stored in short forms How can I have country please let me know I have tried this code but it gives in short form only.

    $collection->getSelect()->join(‘sales_flat_order_address’, ‘main_table.entity_id = sales_flat_order_address.parent_id’,array(‘company’,'country_id’));

    Thanks & Regards
    Srikanth Thandra

    • Anonymous

      you can use own renderer to display full country name at grid.

      First, define it at _prepareColumns():
      $this->addColumn(‘country’, array(
      ‘header’ => Mage::helper(‘sales’)->__(‘Printed’),
      ‘index’ => ‘country_id’,
      ‘type’ => ‘int’,
      ‘width’ => ’40px’,
      ‘renderer’ => ‘Your_Module_Block_Adminhtml_Template_Grid_Renderer_Country’
      ));

      Create renderer class, it should extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Action.
      Use code similar to:
      public function _getValue(Varien_Object $row){
      $country_code = $row->getData($this->getColumn()->getIndex());
      return Mage::app()->getLocale()->getCountryTranslation($country_code);
      }

      • srikanth thandra

        Hi,

        Thanks for you reply but just now I test it for 1.6.2 it does not work it gives error
        Item (Mage_Sales_Model_Order) with the same id “10″ already exist

        please let know. Can you please let me know the code to be added in which file. I am new to magento please help.

        • Anonymous

          Hi, I’ve shared working example for you https://bitbucket.org/vovcheg/atwix/src . The code includes Exgrid module for renderer class and Grid.php (placed to local). New Country column will be added to grid.

          • srikanth thandra

            Hi,

            Thanks you very much that code is working very fine. I need mode help please I have created a attribute in customer account page as “sales person” I have used the help of this url http://www.danneh.org/2011/07/adding-new-attribute-to-customer-account-in-magento/ to create that attribute I want to call that in the admin grid how do I call it Please help me.

            Thanks & Regards,
            Srikanth Thnadra

          • srikanth thandra

            Hi,

            Can you please reply How to add Company and Sales Person please.

            Thanks & Regards,
            Srikanth Thandra

          • Anonymous

            Hi,

            unfortunately we do not provide free Magento development services through this blog. If is only designated for our developers to share their experience and knowledge.

            If you’d like to get an assistance, you may contact us for a quote at hello@atwix.com

            Thank you.

          • srikanth thandra

            Hi,

            I tried to change the code in this way because I wanted company as well so the changes I did are
            $collection->getSelect()->join(‘sales_flat_order_address’, ‘main_table.entity_id = sales_flat_order_address.parent_id’,array(‘company’,'country_id’));

            &

            $this->addColumn(‘company’, array(
            ‘header’ => Mage::helper(‘Sales’)->__(‘Company’),
            ‘index’ => ‘company’,

            ));
            //our custom column
            $this->addColumn(‘country’, array(
            ‘header’ => Mage::helper(‘Sales’)->__(‘Country’),
            ‘index’ => ‘country_id’,
            ‘type’ => ‘text’,
            ‘renderer’ => ‘Atwix_Exgrid_Block_Adminhtml_Template_Grid_Renderer_Country’

            ));

            But company is not getting displayed please let me know what to do and also how to call the customer created attribute as well please let me know.

        • aserty

          $collection->getSelect()
          ->join(
          array(‘address’ => $collection->getTable(“sales/order_address”)),
          ‘main_table.entity_id = address.parent_id AND address.address_type = “shipping”‘,
          array(‘company’)
          );

          Works for me

  • Mansuri Feroz

    Show “There has been an error processing your request” error for magento 1.6.2, plz let me know how to proceed..

    • Anonymous

      give us more details, what actions produce error?

  • vinayak JMS

    Hello nice soln but i need to add color icon for status in sales order grid ??

    I am not able to find the exactly where to code…

    any solution here,need help??

  • Paul

    Works on 1.7.0.1 however when you try and filter the column it redirects back to the dashboard and then when you go back to orders it says the field name does not exist in where clause. Works fine with filter set to false though.

    • http://twitter.com/paugnu Pau Iranzo

      Hi Paul,

      Remember that _prepareCollection() in your module has to return ‘$this’ and _prepareColumns() has to return ‘parent::_prepareColumns();’. I’ve had this problem and finally solved it!

  • http://www.facebook.com/arunrb.83 Rb Arun

    How can I add the color of a ordered item in sales order grid page.. Please help me in this case

    • http://www.facebook.com/arunrb.83 Rb Arun

      How can I display product size, color in sales order grid column..
      Please help me in this case..

  • Dano

    Thank Much for the tips,
    I was able to use the method…
    $collection->getSelect()->join(array(‘address’ => $collection->getTable(“sales/order_address”)),’main_table.entity_id = address.parent_id AND address.address_type = “shipping”‘, array(‘country_id’, ‘region’) );
    to get and display address data…(without throwing the Item (Mage_Sales_Model_Order) with the same id “10″ already exists error)

    I am also trying to get the shipping_description to display, however, it is IN the sales_flat_order table… so If I try to use the join method
    $collection->getSelect()->join(‘sales_flat_order’, ‘main_table.entity_id = sales_flat_order.entity_id’,array(‘shipping_description’));

    The shipping description DOES display… but Admin the form and column sorts will break (I believe because it is joining the main table back to itself)

    So, does anyone know the method to call a field from the main table without the join method?

  • http://twitter.com/SimoneFreelance Simone Chiaromonte

    Thank you very much Volodymyr Vygovskyi,

    Could I ask you the code to retrieve the payment method used in the order?

    Thank you very much
    You deserve a backlink!

    Best Regards
    Simone

    • Volodymyr Vygovskyi

      Hi, Simone. It is pretty simple to insert payment method code to orders grid:
      Join table:
      $collection->getSelect()->join(‘sales_flat_order_payment’, ‘main_table.entity_id = sales_flat_order_payment.parent_id’,array(‘method’) );

      Add column:
      $this->addColumn(‘method’, array(
      ‘header’ => Mage::helper(‘sales’)->__(‘Method’),
      ‘index’ => ‘method’,
      ‘width’ => ’80px’,
      ‘filter_index’ => ‘sales_flat_order_payment.method’,
      ));

      Note that payment method title is not available for easy inserting into orders grid using this method.

    • vovsky

      Hi, Simone. It is pretty simple to insert payment method code to orders grid:
      Join table:
      $collection->getSelect()->join(‘sales_flat_order_payment’, ‘main_table.entity_id = sales_flat_order_payment.parent_id’,array(‘method’) );

      Add column:
      $this->addColumn(‘method’, array(
      ‘header’ => Mage::helper(‘sales’)->__(‘Method’),
      ‘index’ => ‘method’,
      ‘width’ => ’80px’,
      ‘filter_index’ => ‘sales_flat_order_payment.method’,
      ));

      Note that payment method title is not available for easy inserting into orders grid using this method.

  • Sarvagya

    hi vovsky,

    I need to make a column of customer names on transactions grid i have achieved to show first and last name but in a separate column i guess i also need to join collections here my function from transactions grid is here :

    protected function _prepareCollection()
    {

    $collection = ($this->getCollection())
    ? $this->getCollection() : Mage::getResourceModel(‘sales/order_payment_transaction_collection’)
    ->addAttributeToSelect(‘*’);

    $order = Mage::registry(‘current_order’);
    if ($order) {
    $collection->addOrderIdFilter($order->getId());
    }

    $collection->addOrderInformation(array(‘increment_id’));
    $collection->addPaymentInformation(array(‘method’));

    $collection->addOrderInformation(array(‘customer_firstname’,'customer_lastname’,'customer_email’,'customer_id’,”));

    $this->setCollection($collection);
    return parent::_prepareCollection();
    }

    Please help,
    Thanks in advance

  • http://www.facebook.com/rafael.triolo.1 Rafael Triolo

    Hi there , is a great code. When a i put your code on my local magento instalation , this works fine. But when a try to put on my on-line store, i get the error “Item (Mage_Sales_Model_Order) with the same id “74″ already exist”. Can you help me with this?

    • vovsky

      Hi, Rafael!. It seems like multiple columns with same id are being selected in _prepareCollection method in your case. Adding $collection->getSelect()->group(‘entity_id’) before $this->setCollection($collection) may fix your problem.

      • http://www.facebook.com/rafael.triolo.1 Rafael Triolo

        Hi works fine , but in the code group(‘entity_id’) i put (‘main.entity_id’) because i´m still having a error . For now it´s ok. Tks again

      • Daniel Martínez

        Hi there. I submitted this question to stackoverflow http://stackoverflow.com/questions/14515338/adding-custom-columns-in-order-grid-magento-1-7-0-0, but I’ll post it here anyway. Basically I had the same problem Rafael mentioned above, and I did what you recommended (and what he corrected above), but even though the columns are populated, the pagination is messed up and there’s no way to look things up in the order grid. What do you think it’s causing this?

  • http://www.facebook.com/rafael.triolo.1 Rafael Triolo

    Hi there it´s me again lol. When i tryed to do the ‘sku’ code, i´ve got a duplicate results on my column. Can you help me with this? i have already tryed the function ‘group’ , but still doesn´t work. Tks again

  • Scott

    This is awesome just what I needed .. any chance you have a post on how to remove columns from the grid like the “Attrib. Set Name” that I will never use?

    • vovsky

      Hi, Scott!
      There is a method removeColumn($columnId). If you are looking for a quick solution you can place a code like this:
      $this->removeColumn(‘shipping_name’); //your column_id as parameter
      to the end of _prepareColumns() function.
      I’m going to describe a better way of doing this in the next article. Stay tuned.

  • Ganga Bohara

    It saved a lot of time for me. Thank you

  • Jimmy T

    This has saved me a ton of time. Do you know which table in the DB I should be looking at to know which attributes I can use?

  • banningstuckey

    I tried using your code above and it seems to work very well.. however now when I try to do a date range search I get this error ”

    SQLSTATE[23000]: Integrity constraint violation: 1052 Column ‘created_at’ in where clause is ambiguous” … i can only assume its because
    created_at exists in both tables?

  • http://www.facebook.com/profile.php?id=100005094181544 Dmitry Zarudnev

    Hello I’m adding additional columns does not properly be considered the total number of orders. I am looking for a solution, but so far No results. Magento 1.7.0.2