Understanding Magento Order Processing: How Products are Saved
When an order is placed on your Magento store, you might be wondering exactly how the ordered products get saved into the database. In this post, we’ll walk through the process behind the scenes and explore how to save additional product attributes like regular prices.
Magento’s Order Saving Process
Step 1: Cart Validation
The order saving process begins when a customer goes through checkout. First, the cart is validated in app/code/core/Mage/Checkout/controllers/OnepageController.php. If the cart passes validation:
$cart->save();
Step 2: Order Creation and Saving
Next, an instance of the sales/service ORDER class is created and populated with data from the cart. The order details are then saved into the database using $order->save().
// Create new order
$order = Mage::getModel('sales/order');
// Populate order data from cart
...
// Save the order to the database
$order->setIsValid(true);
$order->place();
Step 3: Saving Order Items
After the main order is saved, each ordered item (product) needs to be associated with it. This happens in the following loop:
foreach ($cartItems as $itemId => $data) {
// Create a new order item and populate its data from the cart item
$orderItem = Mage::getModel('sales/order_item')
->setOrder($order)
->setOrderItemId(null)
->addData(array(
'product_id' => $item->getProductId(),
...
));
// Save the order item to the database
$orderItem->save();
}
Saving Additional Product Attributes
By default, Magento only saves the special price for ordered items if a special price is configured. To save the regular price as well, you’ll need to override the core functionality.
Overriding the Core Model
To achieve this, create an extension that overrides Mage_Sales_Model_Order_Item in your local configuration file (app/etc/local.xml). Then implement a custom model with additional logic:
<config>
<global>
<models>
<sales>
<rewrite>
<order_item>Company_Magento_Helper_Model_Order_Item</order_item>
</rewrite>
</sales>
</models>
</global>
</config>
Modify the Custom Model
In your custom model, you can add logic to save additional product attributes:
public function save()
{
// Save regular price before saving the order item
$this->setRegularPrice($this->getProduct()->getPrice());
return parent::save();
}
Conclusion
Understanding how Magento saves ordered products is crucial for customizing the order processing workflow. By overriding core models, you can modify this process to suit your specific business needs.
Remember that modifying Magento’s core files directly is generally not recommended due to upgrade issues. Using an extension or custom module allows you to maintain a clean separation of concerns and makes it easier to update to new Magento versions in the future.
To learn more about extending Magento functionality safely, check out our guide on Magento Extension Development at LaravelCompany.