Adding Cash on Delivery Price Programmatically in Magento
In this post, we’ll guide you through adding a cash on delivery (COD) price to an order created programmatically in Magento. This involves setting the COD fee and ensuring it appears correctly in the admin panel.
Understanding the Cash on Delivery Process
When you create an order manually via the Magento admin interface and select “Cash On Delivery” as the payment method, Magento automatically adds a row for the COD fee to the Order Totals column. This is handled by adding a value to the cod_fee field in the sales_flat_order table.
Adding Cash on Delivery Fee Programmatically
To add a COD fee when creating an order programmatically, you’ll need to set this value manually since the payment method selection isn’t triggered by your custom module.
First, retrieve the configured COD fee from the Magento configuration settings:
$codFee = Mage::getStoreConfig('payment/cashondelivery/fee');
Next, when creating your order model, add a line to set the cod_fee field:
$order->setCodFee($codFee);
This ensures that the COD fee is recorded in your database.
Ensuring the COD Fee Displays Correctly
To have Magento display the COD fee with a proper label (“Cash On Delivery Fee”) in the Order Totals column of the admin panel, you’ll need to override the getTotals() method in one of your order models. This can be done using an observer or by extending the core model.
Here’s an example of overriding the getTotals() method:
public function getTotals()
{
$totals = parent::getTotals();
if (isset($totals['tax'])) {
foreach ($totals['tax'] as &$tax) {
if ($tax['title'] == 'Cash On Delivery Fee') {
$tax['total'] += $this->getCodFee();
}
}
}
return $totals;
}
This code checks for the “Cash On Delivery Fee” total and adds your COD fee to it.
Conclusion
Adding a cash on delivery price programmatically in Magento requires setting the cod_fee field manually during order creation. To ensure the COD fee displays correctly in the admin panel, you need to override the getTotals() method in an appropriate order model.
Remember to test your changes thoroughly and consider using a development environment first before applying them to your live site.
For more advanced Magento customizations and extensions, check out Laravel Company. We specialize in providing high-quality Magento solutions for businesses of all sizes.