Magento: Adding custom attributes to orders, Part II

In hindsight I probably should have tested the method I blogged about recently, just to make sure it works.

Because it doesn’t.

In hindsight I probably should have tested the method I blogged about recently, just to make sure it works.

Because it doesn’t.

Oh, the EAV attribute is created all right. But it’s useless, because as I learned since then, orders do not read from the EAV tables since Magento 1.4 (released end of 2010, maybe). They use a flat table ({sales_flat_order}) along with a bunch of other flat tables (order items, quotes, invoices…).

What to do? There are a couple of options. I could add a field to that flat table. Easy to do with an install script, something like:

$installer->run("ALTER TABLE ADD my_custom_field VARCHAR(500);");

Problem is, according to one poster on Stack Overflow, that’s probably not upgrade safe. Plan B would be to create a separate table, keyed on Order ID. Easy enough to do, and my first plan was to write the to the custom as the info is copied from the quote to the order, in Mage_Sales_Model_Convert_Quote::toOrder().

But that doesn’t look possible, because the Order ID isn’t set yet. Seems crazy, I know, but I tried to read

$order->getIncrementId() //I know that one's set
$order->getId() //Nope
$order->getOrderId() //Not that either
$order->getEntityId() //Because the order table's primary key field is entity_id

So I could use increment_id (not exactly sure what that field is good for, except for displaying to customers)… but then I decided to just key the custom table on quote_id. No need to worry about writing to the order, I just extend the order model like so:

class Npd_Myextension_Model_Sales_Order extends Mage_Sales_Model_Order
{
    public function getCustomField() {
    	$quote = Mage::getSingleton('sales/quote');
	$quote->load($this->getQuoteId());
   	return $quote->getCustomField();
    }
}

Which works, because orders always keep a reference to their source quote. Likewise, invoices keep a reference to their source order.

So there you go, and I’m making progress. Progress against a massive headwind, mind you. Again, I whine: why the hell is Magento making things so hard for developers?

PS: about the order ID, am I just kind of dim, or is it actually not set at that point? If it is, what getter function should my code be using? The fact that I’m even asking “what getter function should I be using?” shows either Magento or myself needs serious help…