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')
->setIncrementId($reservedOrderId)
->setStoreId($storeId)
->setQuoteId(0)
->setGlobal_currency_code('USD')
->setBase_currency_code('USD')
->setStore_currency_code('USD')
->setOrder_currency_code('USD');
//Set your store currency USD or any other

// set Customer data
$order->setCustomer_email($customer->getEmail())
->setCustomerFirstname($customer->getFirstname())
->setCustomerLastname($customer->getLastname())
->setCustomerGroupId($customer->getGroupId())
->setCustomer_is_guest(0)
->setCustomer($customer);

// set Billing Address
$billing = $customer->getDefaultBillingAddress();
$billingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultBilling())
->setCustomer_address_id($billing->getEntityId())
->setPrefix($billing->getPrefix())
->setFirstname($billing->getFirstname())
->setMiddlename($billing->getMiddlename())
->setLastname($billing->getLastname())
->setSuffix($billing->getSuffix())
->setCompany($billing->getCompany())
->setStreet($billing->getStreet())
->setCity($billing->getCity())
->setCountry_id($billing->getCountryId())
->setRegion($billing->getRegion())
->setRegion_id($billing->getRegionId())
->setPostcode($billing->getPostcode())
->setTelephone($billing->getTelephone())
->setFax($billing->getFax());
$order->setBillingAddress($billingAddress);

$shipping = $customer->getDefaultShippingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultShipping())
->setCustomer_address_id($shipping->getEntityId())
->setPrefix($shipping->getPrefix())
->setFirstname($shipping->getFirstname())
->setMiddlename($shipping->getMiddlename())
->setLastname($shipping->getLastname())
->setSuffix($shipping->getSuffix())
->setCompany($shipping->getCompany())
->setStreet($shipping->getStreet())
->setCity($shipping->getCity())
->setCountry_id($shipping->getCountryId())
->setRegion($shipping->getRegion())
->setRegion_id($shipping->getRegionId())
->setPostcode($shipping->getPostcode())
->setTelephone($shipping->getTelephone())
->setFax($shipping->getFax());

$order->setShippingAddress($shippingAddress)
->setShipping_method('flatrate_flatrate');
/*->setShippingDescription($this->getCarrierName('flatrate'));*/
/*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')
->setStoreId($storeId)
->setCustomerPaymentId(0)
->setMethod('purchaseorder')
->setPo_number(' – ');
$order->setPayment($orderPayment);

// 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')
->setStoreId($storeId)
->setQuoteItemId(0)
->setQuoteParentItemId(NULL)
->setProductId($productId)
->setProductType($_product->getTypeId())
->setQtyBackordered(NULL)
->setTotalQtyOrdered($product['rqty'])
->setQtyOrdered($product['qty'])
->setName($_product->getName())
->setSku($_product->getSku())
->setPrice($_product->getPrice())
->setBasePrice($_product->getPrice())
->setOriginalPrice($_product->getPrice())
->setRowTotal($rowTotal)
->setBaseRowTotal($rowTotal);

$subTotal += $rowTotal;
$order->addItem($orderItem);
}

$order->setSubtotal($subTotal)
->setBaseSubtotal($subTotal)
->setGrandTotal($subTotal)
->setBaseGrandTotal($subTotal);

$transaction->addObject($order);
$transaction->addCommitCallback(array($order, 'place'));
$transaction->addCommitCallback(array($order, 'save'));
$transaction->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]';
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
if(!$customer->getId()) {
	$groups = Mage::getResourceModel('customer/group_collection')->getData();
	$groupID = '3';

	$customer->setData( 'group_id', $groupID );
	$customer->setEmail($email);
	$customer->setFirstname('test');
	$customer->setLastname('testing');
	$customer->setPassword($password);

	$customer->setConfirmation(null);
	$customer->save();

	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 {
if(!$order->canInvoice())
{
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.'));
}
 
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
//Or you can use 
//$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
 
$transactionSave->save();
}
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) {
 print_r($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()) {
            $this->_fault('order_not_exists');
        }
        if (!$order->canCreditmemo()) {
            $this->_fault('cannot_create_creditmemo');
        }
        $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()) {
                $this->_fault('cannot_refund_to_storecredit');
            }
            $refundToStoreCreditAmount = max(
                0,
                min($creditmemo->getBaseCustomerBalanceReturnMax(), $refundToStoreCreditAmount)
            );
            if ($refundToStoreCreditAmount) {
                $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice($refundToStoreCreditAmount);
                $creditmemo->setBaseCustomerBalanceTotalRefunded($refundToStoreCreditAmount);
                $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice(
                    $refundToStoreCreditAmount*$order->getStoreToOrderRate()
                );
                // this field can be used by customer balance observer
                $creditmemo->setBsCustomerBalTotalRefunded($refundToStoreCreditAmount);
                // setting flag to make actual refund to customer balance after credit memo save
                $creditmemo->setCustomerBalanceRefundFlag(true);
            }
        }
        $creditmemo->setPaymentRefundDisallowed(true)->register();
        // add comment to creditmemo
        if (!empty($comment)) {
            $creditmemo->addComment($comment, $notifyCustomer);
        }
        try {
            Mage::getModel('core/resource_transaction')
                ->addObject($creditmemo)
                ->addObject($order)
                ->save();
            // 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

  • http://redesigned.com redesigned

    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?

    Thanks!!!

  • http://www.udaantechnologies.com/ web design india

    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 http://www.excellencemagentoblog.com/useful-code-snippets instead of http://www.excellencemagentoblog.com/blog/index/index/id/45,

    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

  • http://www.facebook.com/hkhalid101 Humayun Chaudhary

    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’);
    $method->setCarrier(“excellence_excellence”);
    $method->setMethod(“excellence_excellence”);
    $method->setCarrierTitle(“”);
    $method->setMethodTitle(“”);
    $method->setPrice($myValue);
    $method->setCost($myValue);
    $result->append($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?

    Thanks

  • 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.

    Regards,
    Naitik