Magento – Add invoice status to order grid

adminhtmlcollection;gridmagento-1.7

We try to add the invoice status column to the sales order grid.

We added the code beneath to the prepareCollection function:

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

And the code beneath to the prepareColumns function:

$this->addColumn('state', array(
    'header'    => Mage::helper('sales')->__('Invoice Status'),
    'index'     => 'state',
    'type'      => 'options',
    'options'   => Mage::getResourceModel('sales/order_invoice_collection')->addAttributeToSelect('state'),
));

We got the following error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sales_flat_invoice.parent_id' in 'on clause'

What is going wrong?

Best Answer

Firstly - be careful with joining live tables on your sales_order_grid in the admin view. The reason is simple - any action or long-running query that your admins might be executing (for instance, sorting by a custom unindexed column with no other filters and 300k+ orders) may cause locks for your join table and prevent production orders.

Your column defines this as type of options but the option list you're providing is the entire invoice collection!!!

Out of the box, invoice state is only 1 of 3 potential values:

/**
 * Invoice states
 */
const STATE_OPEN       = 1;
const STATE_PAID       = 2;
const STATE_CANCELED   = 3;

So you can handle it one of two ways - explicitly state the options:

'type'      => 'options',
'options'   => array(
    '1' => Mage::helper('core')->__('Open'),
    '2' => Mage::helper('core')->__('Paid'),
    '3' => Mage::helper('core')->__('Canceled'),
),

Or, use something handy that Magento provides -- a static method for all invoice states in case they differ from version to version:

'type'      => 'options',
'options'   => Mage_Sales_Model_Order_Invoice::getStates()

I prefer the latter as I am not a fan of typing out array options manually :)

Cheers.

Related Topic