Useful Code Snippets

In this blog, i will share some advanced useful code snippets which come into use when developing custom modules

Create Order

Below is the php code to create an order in magento. It requires a valid customer account with shipping and billing address setup.

$id=1; // get Customer Id
$customer = Mage::getModel('customer/customer')->load($id);

$transaction = Mage::getModel('core/resource_transaction');
$storeId = $customer->getStoreId();
$reservedOrderId = Mage::getSingleton('eav/config')->getEntityType('order')->fetchNewIncrementId($storeId);

$order = Mage::getModel('sales/order')
//Set your store currency USD or any other

// set Customer data

// set Billing Address
$billing = $customer->getDefaultBillingAddress();
$billingAddress = Mage::getModel('sales/order_address')

$shipping = $customer->getDefaultShippingAddress();
$shippingAddress = Mage::getModel('sales/order_address')

/*some error i am getting here need to solve further*/

//you can set your payment method name here as per your need
$orderPayment = Mage::getModel('sales/order_payment')
->setPo_number(' – ');

// let say, we have 1 product
//check that your products exists
//need to add code for configurable products if any
$subTotal = 0;
$products = array(
    '1' => array(
    'qty' => 2

foreach ($products as $productId=>$product) {
$_product = Mage::getModel('catalog/product')->load($productId);
$rowTotal = $_product->getPrice() * $product['qty'];
$orderItem = Mage::getModel('sales/order_item')

$subTotal += $rowTotal;


$transaction->addCommitCallback(array($order, 'place'));
$transaction->addCommitCallback(array($order, 'save'));

Creating Customer

Below is a php code to create a customer account in magento.

$customer = Mage::getModel('customer/customer');
$password = 'test1234';
$email = '[email protected]';
if(!$customer->getId()) {
	$groups = Mage::getResourceModel('customer/group_collection')->getData();
	$groupID = '3';

	$customer->setData( 'group_id', $groupID );


	echo $customer->getId();

Creating Invoice

Below is a php code to create invoice for an order in magento.

$order = Mage::getModel('sales/order')->loadByIncrementId('100000001');
try {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
//Or you can use 
$transactionSave = Mage::getModel('core/resource_transaction')
catch (Mage_Core_Exception $e) {

Create Shipment

Below is a php code to create a shipment for an order in magento.

$order = Mage::getModel('sales/order')->loadByIncrementId('100000001');
try {
	if($order->canShip()) {
		//Create shipment
		$shipmentid = Mage::getModel('sales/order_shipment_api')
						->create($order->getIncrementId(), array());
		//Add tracking information
		$ship = Mage::getModel('sales/order_shipment_api')
						->addTrack($order->getIncrementId(), array());		
}catch (Mage_Core_Exception $e) {

Creating Credit Memo

Below is a php code to create a credit memo for an order in magento.

$order = Mage::getModel('sales/order')->load('100000001', 'increment_id');
        if (!$order->getId()) {
        if (!$order->canCreditmemo()) {
        $data = array();

        $service = Mage::getModel('sales/service_order', $order);
        $creditmemo = $service->prepareCreditmemo($data);

        // refund to Store Credit
        if ($refundToStoreCreditAmount) {
            // check if refund to Store Credit is available
            if ($order->getCustomerIsGuest()) {
            $refundToStoreCreditAmount = max(
                min($creditmemo->getBaseCustomerBalanceReturnMax(), $refundToStoreCreditAmount)
            if ($refundToStoreCreditAmount) {
                $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice($refundToStoreCreditAmount);
                $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice(
                // this field can be used by customer balance observer
                // setting flag to make actual refund to customer balance after credit memo save
        // add comment to creditmemo
        if (!empty($comment)) {
            $creditmemo->addComment($comment, $notifyCustomer);
        try {
            // send email notification
            $creditmemo->sendEmail($notifyCustomer, ($includeComment ? $comment : ''));
        } catch (Mage_Core_Exception $e) {
            $this->_fault('data_invalid', $e->getMessage());
        echo $creditmemo->getIncrementId();
These are only few code snippets. If you need any more additional code snippets let me know i will add them or you can your self submit more code snippets and i will publish them.
  • Magento Modules

    Thanks, any code to override default price for magento

  • Manish,

    Thank you so much for your wonderful posts, they are very helpful.

    Question: How would one add a country and region select to admin form, ideally where the region list updates dynamically when a country country is selected?

    I’m trying to allow admins to edit and enter new customer addresses in a module i’m creating.
    Any tips?


  • Thank
    you! This is something I needed to learn right now.

  • Shawn

    Hi Manish,

    I love your webste very much as well as the url rewrite,

    currently, i’m using zend framework to build my own blog, the thing bothers me very much is i want the same url as yours instead of,

    how can I do it in zend? Not magento, apprecite if you could help me out.

  • Mont

    How do you remove a customer incl his address(es)?

  • gaurav

    how to use these code and where to use i.e means page or folder

  • How can i create partial create memo? i.e. if total order value is £50 and I want to create a credit memo of £10. In the above code, even if I set the $refundToStoreCreditAmount = 10; it still refunds the full amount. Any idea how to refund partially?

  • Manish Prakash

    Hi Steve,
    Yes that’s possible.

  • Nitin Pant

    Hi Manish, Can you please help me on this?

    I am trying to calculate shipping price based on dimensions,
    post code and type of parcel(regular/express). I am able to calculate
    that using AUSPOST api but the problem is to save the shipping rate
    outside of the collectRates method in magento. If I do this…

    $result = Mage::getModel(‘shipping/rate_result’);

    $method = Mage::getModel(‘shipping/rate_result_method’);

    It does not work because the $result has to be saved in the quote. What can I do?

  • posh webdevelopment

    Thanks to share the useful snippets code..

  • dave

    useful and easy code snipped would be one to produce a COMPLETE address (might even be worth overriding tostring in Mage_Sales_Model_Order_Address) – I don’t get why it isn’t there already tbh. Sure it only takes two or three minutes to write one but it’s an irritating omission from magento imo

  • gurjit

    Hi Manish,

    Do you have any idea how we can implement manage taxes with create custom order?


  • Omi

    Exellent thank you soo much for this great help!

  • Naitik

    Hello Sir,

    I have to import orders data from ASP.NET site and we have available demo which fields are required to store our magento database.

    We have created root script and import all order details with it but Payment Method like Authorised.NET and Paypal details are not saved for the particular information of order.

    We are using multisite in Magento EE version but we have to import order with all details on second store.
    will it possible or not?

    So, Can you give me any suggestion from your side?

    Let me know if you have any query for the same.

    I’m waiting your response.