Adminhtml Grid – How to Add New Column to Sales Flat Order Grid

adminhtmlgridgrid-serlizationorder-grid

How can I add a new column to the sales_flat_order_grid table and ensure that values are properly inserted there?

The "source" for the new column is a custom column we've added to sales_flat_order, let's call it foo. AFAICT, there are three ways to get foo to appear in the main order grid:

  1. JOIN the sales_flat_order_grid collection onto sales_flat_order.
    • Problem: Filters no longer work due to ambiguous columns (since both tables have similar column names)
  2. Have the grid use sales_flat_order for data instead of sales_flat_order_grid.
    • Problem: Columns aren't indexed, so filtering is dreadfully slow. It seems silly to add index the same data indexed in the unused sales_flat_order_grid table.
  3. Add a new column to sales_flat_order_grid and ensure the value updates there

I cannot figure out how sales_flat_order_grid is being updated, therefore I don't know how to add this new column. Any thoughts?

Best Answer

The sales_flat_order_grid table is updated at every order save action. You can add custom columns to the table in your own extension, if you add a column name that is already used in the sales_flat_order table you do not need to add anything extra, on every order-save action the columns are updated (if needed). If you want to insert data from a different table you will need to create an observer for the sales_order_resource_init_virtual_grid_columns event to collect and prepare the join.

For more details and a working example see my answer in Add Column to a grid (observer) - Column ‘store_id’ in where clause is ambiguous issue