19

I'm trying to add a custom field to my orders. At this moment, I found the post bellow that helped me to create such attribute in my database: http://fabrizioballiano.net/2011/11/15/create-a-custom-order-attribute-in-magento/

require_once('app/Mage.php');
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));

$installer = new Mage_Sales_Model_Mysql4_Setup;
$attribute  = array(
   'type'          => 'int',
   'backend_type'  => 'text',
   'frontend_input' => 'text',
   'is_user_defined' => true,
   'label'         => 'My Label',
   'visible'       => true,
   'required'      => false,
   'user_defined'  => true,
   'searchable'    => true,
   'filterable'    => true,
   'comparable'    => true,
   'default'       => 0
);
$installer->addAttribute('order', 'special_attribute', $attribute);
$installer->endSetup();

After executing the code above and creating several orders, I'm able to loop through all orders and see the default value to the every order.

The question is, how can I store the data I want in this field? How can I retrieve such data?

Thanks!

MatheusJardimB
  • 3,599
  • 7
  • 46
  • 70

1 Answers1

29

Add this to the gobal scope in config.xml. Then simply set the attribute in the quote - it gets automagically transferred to the order in the quote to order conversion process.

<global>
...
    <fieldsets>
        <sales_convert_quote>
            <your_special_attribute>
                <to_order>*</to_order>
            </your_special_attribute>
        </sales_convert_quote>
    </fieldsets>
...
</global>

You can retrieve/set the attribute at any time via the magic getter/setter e.g.

$quote->getYourSpecialAttribute()
$order->getYourSpecialAttribute()

$quote->setYourSpecialAttribute()
durron597
  • 31,968
  • 17
  • 99
  • 158
Michael Leiss
  • 5,395
  • 3
  • 21
  • 27
  • 2
    My problem now is: did it worked only because I've added your xml lines or mine have also contributed? – MatheusJardimB Jul 11 '13 at 18:50
  • 4
    of course...you added the attribute via your installer script. the xml lines i gave you push the attribute automatically through the quote to order conversion. as quote is also saved in db you should create the attribute in quote too! just check the sales order quote db table. – Michael Leiss Jul 11 '13 at 19:39
  • As you said both get and set working fine inside sales_order_sales_after observer but when i tried this $orders = Mage::getResourceModel('sales/order_collection')->addFieldToSelect('*')->addAttributeToFilter("your_special_attribute", array("finset"=>$customer_id))->setOrder('created_at', 'desc'); It's Not working. – pravat231 Sep 18 '14 at 07:39
  • @JeevaRathinam: what do you mean with proper code? This is about automatically transfering an attribute being in the quote object to the order object via configuration xml - thus no further code is needed. – Michael Leiss Jul 12 '17 at 07:40