Category: Magento

How to add custom block after items block into order view page in magento

In order view page, add a custom block after any type of block. Here I show you, how you can create a block after items block. You can visit my previous post overwrite sales order view. So lets start.

Suppose namespace is “Exercise” and module name is “CustomSales”

Step 1 : Create a module config file into app/etc/modules/Exercise_CustomSales.xml

<config>
    <modules>
        <Exercise_CustomSales>
            <active>true</active>
            <codePool>local</codePool>
        </Exercise_CustomSales>
    </modules>
</config>

Step 2: Create a config file under app/code/local/Exercise/CustomSales/etc/config.xml

<config>
    <modules>
        <Exercise_CustomSales>
            <version>1.7.0.2</version>
        </Exercise_CustomSales>
    </modules>
    <adminhtml>
        <layout>
            <updates>
                <customsales>
                    <file>exercise_customsales.xml</file>
                </customsales>
            </updates>
        </layout>
    </adminhtml>
    <global>
        <blocks>
            <customsales>
                <class>Exercise_CustomSales_Block</class>
            </customsales>
        </blocks>
    </global>
</config>

Step 3: Create a block app/code/local/Exercise/CustomSales/Block/Sales/Order/View/Custom.php

class Exercise_CustomSales_Block_Sales_Order_View_Custom extends Mage_Core_Block_Template
{
    
}

Step 4: Create a layout config file app/design/adminhtml/default/default/layout/exercise_customsales.xml

<layout version="0.1.0">
    <adminhtml_sales_order_view>
        <reference name="order_items">
            <action method="setTemplate"><template>customsales/sales/order/view/items.phtml</template></action>
            <block type="customsales/sales_order_view_custom" name="customsales_sales_order_view_custom" template="customsales/sales/order/view/custom.phtml"/>
        </reference>
    </adminhtml_sales_order_view>
</layout>

Step 4: Copy sales/order/view/items.phtml into customsales/sales/order/view/items.phtml
Open this file and add one line code, look like,

<div class="grid np">
......
......
</div>
<br />
<?php echo $this->getChildHtml('customsales_sales_order_view_custom');?>

Step 5: Create a new file customsales/sales/order/view/custom.phtml, you can add your custom content. Clear cache and go to order view page.

Enjoy magento code!

Adding links to top menu in magento

In magento frontend, top menu is fact for customer need. When you add some menu without category then is a fact to add menu. Here I add a menu programmatically with top menu. Following step can add a menu.

Suppose Namespace is “Exercise” and module name is “FrontendMenu” and CodePool is “local”

Step 1: Create a module config file into app/etc/modules/Exercise_FrontendMenu.xml

<config>
    <modules>
        <Exercise_FrontendMenu>
            <active>true</active>
            <codePool>local</codePool>
        </Exercise_FrontendMenu>
    </modules>
</config>

Step 2: Create a config file under app/code/local/Exercise/FrontendMenu/etc/config.xml

<config>
    <modules>
        <Exercise_FrontendMenu>
            <version>0.1.0</version>
        </Exercise_FrontendMenu>
    </modules>
    <global>
        <blocks>
            <frontendmenu>
                <class>Exercise_FrontendMenu_Block</class>
            </frontendmenu>
        </blocks>
        <models>
            <frontendmenu>
                <class>Exercise_FrontendMenu_Model</class>
            </frontendmenu>
        </models>
    </global>
    <frontend>
        <events>
            <page_block_html_topmenu_gethtml_before>
                <observers>
                    <frontendmenu>
                        <class>frontendmenu/observer</class>
                        <method>addToTopmenu</method>
                    </frontendmenu>
                </observers>
            </page_block_html_topmenu_gethtml_before>
        </events>
    </frontend>
</config>

Step 3 : Create a observer into app/code/local/Exercise/FrontendMenu/Model/Observer.php

class Exercise_FrontendMenu_Model_Observer
{
    public function addToTopmenu(Varien_Event_Observer $observer)
    {
        $menu = $observer->getMenu();
        $tree = $menu->getTree();
        // create a menu tree node
        $node = new Varien_Data_Tree_Node(array(
            'name'   => 'Products',
            'id'     => 'products',
            'url'    => Mage::getUrl('products') // Link url
        ), 'id', $tree, $menu);
        // add node to menu
        $menu->addChild($node);
    }
}

That’s it! Magento is always beautiful 🙂

Get Ready For Magento Certified Developer Exam

By 2nd February, 2014 I gave my magento certification exam and pass with score 69 of 70. I share some information about preparation exam.

For passing or getting good score in this exam, you must have very decent experience in Magento.

1. Get a study guide under resource tab http://www.magentocommerce.com/certification/

2. I went through the Fundamentals of Magento videos available on Magento website.
http://www.magentocommerce.com/training/on-demand

3. Here some excellent tutorial that great help of exam.
http://alanstorm.com/category/magento

http://blog.belvg.com/category/magento-news/developer-certification

Best of luck!

How to rewrite one page checkout success block

We suppose create a new module, name is MyModule and NameSpace is Posixtech.

Step 1: Create a xml file inside this location app/etc/modules/Posixtech_MyModule.xml.

example :

<config>
	<modules>
		<Posixtech_MyModule>
			<active>true</active>
			<codePool>local</codePool>
		</Posixtech_MyModule>
	</modules>
</config>

Step 2: Create a config file inside this location app/code/local/Posixtech/MyModule/etc/config.xml
example :

<?xml version="1.0"?>
<config>
	<modules>
		<Posixtech_MyModule>
			<version>1.0.1</version>
		</Posixtech_MyModule>
	</modules>
    <frontend>
        <routers>
            <mymodule>
                <use>standard</use>
                <args>
                    <module>Posixtech_MyModule</module>
                    <frontName>mymodule</frontName>
                </args>
            </mymodule>
        </routers>
        <layout>
            <updates>
                <mymodule>
                    <file>mymodule.xml</file>
                </mymodule>
            </updates>
        </layout>
    </frontend>
    <global>
        <blocks>
            <mymodule>
                <class>Posixtech_MyModule_Block</class>
            </mymodule>
            <checkout>
                <rewrite>
                    <onepage_success>Posixtech_MyModule_Block_Onepage_Success</onepage_success>
                </rewrite>
            </checkout>
        </blocks>
    </global>
</config>

Step 3: Then we have to create this block (into our module) that should be exdends from Mage_Checkout_Block_Onepage_Success, inside the location app/code/local/Posixtech/MyModule/Block/Onepage/Success.php

example:
class Posixtech_MyModule_Block_Onepage_Success extends Mage_Checkout_Block_Onepage_Success
{
// Write your custom methods
// All parent’s methods also will work
}

Step 4: Create a new xml file for frontend and location is app/design/frontend/base/default/layout/mymodule.xml
example:

<?xml version="1.0"?>
<layout version="0.1.0">
    <checkout_onepage_success translate="label">
        <label>One Page Checkout Success</label>
        <reference name="root">
            <action method="setTemplate"><template>page/2columns-right.phtml</template></action>
        </reference>
        <reference name="content">
            <reference name="checkout.success">
                <action method="setTemplate"><template>mymodule/success.phtml</template></action>
            </reference>
        </reference>
    </checkout_onepage_success>
</layout>

Step 5: Create a file inside this location app/design/frontend/base/default/template/mymodule/success.phtml

You can customize phtml file content without editing base file.

That’s it!

Trouble creating a quote/order through custom code (programmatically create order without use API)

Today’s post is most important. When you create a custom order programmatically , then this post is for you. Magento is really beautiful if you use it otherwise it is horrible 🙂 .I always love to hack magento. So lets start. Bellow this code is only for loged In user.

This example for only “direct post type payment method”, don’t try any payment method that’s redirect to payment site.

This example cover only simple and downloadable product

// get logged in cusomer id
$customerAccountNo = Mage::getModel('customer/session')->getCustomer()->getId();
// load customer object
$customerObj = Mage::getModel('customer/customer')->load($customerAccountNo);
// assign this customer to quote object, before any type of magento order, first create quote.
$quoteObj = Mage::getModel('sales/quote')->assignCustomer($customerObj);
$quoteObj = $quoteObj->setStoreId(Mage::app()->getStore()->getId());

// product id
$productId = 167;
$productModel = Mage::getModel('catalog/product');
$productObj = $productModel->load($productId);

// for simple product
if ($productObj->getTypeId() == 'simple') {
    $quoteObj->addProduct($productObj , 1);
    // for downloadable product
} else if ($productObj->getTypeId() == 'downloadable') {
    $params = array();
    $links = Mage::getModel('downloadable/product_type')->getLinks( $productObj );
    $linkId = 0;
    foreach ($links as $link) {
        $linkId = $link->getId();
    }
    $params['product'] = $productId;
    $params['qty'] = $qty;
    $params['links'] = array($linkId);
    $request = new Varien_Object();
    $request->setData($params);
    $quoteObj->addProduct($productObj , $request);
}
// sample billing address
$billingAddress = array
(
    'email' => NULL,
    'firstname' => "FirstName",
    'lastname' => "LastName",
    'telephone' => "102920",
    'street' => "517 4th Avenue",
    'country_id' => "US",
    'city' => 'San Diego',
    'postcode' => "90001",
    'region_id' => "12",
    'region' => 'California',
    'company' => "Company",
    'fax' => "123445",
    'customer_address_id' => NULL,
);

$quoteBillingAddress = Mage::getModel('sales/quote_address');
$quoteBillingAddress->setData($billingAddress);
$quoteObj->setBillingAddress($quoteBillingAddress);

//if product is not virtual
if (!$quoteObj->getIsVirtual()) {
    $shippingAddress = $billingAddress;
    $quoteShippingAddress = Mage::getModel('sales/quote_address');
    $quoteShippingAddress->setData($shippingAddress);
    $quoteObj->setShippingAddress($quoteShippingAddress);
    // fixed shipping method
    $quoteObj->getShippingAddress()->setShippingMethod('flatrate_flatrate');
    $quoteObj->getShippingAddress()->setCollectShippingRates(true);
    $quoteObj->getShippingAddress()->collectShippingRates();
}

$quoteObj->collectTotals();
$quoteObj->save();


$transaction = Mage::getModel('core/resource_transaction');
if ($quoteObj->getCustomerId()) {
    $transaction->addObject($quoteObj->getCustomer());
}
$transaction->addObject($quoteObj);
$quoteObj->reserveOrderId();

$ccInfo = array();
// assign payment method
$payment_method = 'authorizenet';
if ($payment_method == "authorizenet") {
    $quotePaymentObj = $quoteObj->getPayment();
    $quotePaymentObj->setMethod('authorizenet');
    $quoteObj->setPayment($quotePaymentObj);
    $cc_number = '4111111111111111';
    $quoteObj->getPayment()->setCcNumber($cc_number);
    $quoteObj->getPayment()->setCcType('VI');
    $quoteObj->getPayment()->setCcExpMonth("12");
    $quoteObj->getPayment()->setCcExpYear("2018");
    $quoteObj->getPayment()->setCcLast4(substr($cc_number,-4));
    $quoteObj->getPayment()->setCcCid('123');
} else {
    $quotePaymentObj = $quoteObj->getPayment();
    $quotePaymentObj->setMethod($order->getPayment()->getMethod());
    $quoteObj->setPayment($quotePaymentObj);
}

$convertQuoteObj = Mage::getSingleton('sales/convert_quote');
if ($quoteObj->getIsVirtual()) {
    $orderObj = $convertQuoteObj->addressToOrder($quoteObj->getBillingAddress());
} else {
    $orderObj = $convertQuoteObj->addressToOrder($quoteObj->getShippingAddress());
}

$orderPaymentObj = $convertQuoteObj->paymentToOrderPayment($quotePaymentObj);

$orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getBillingAddress()));
$orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
if (!$quoteObj->getIsVirtual()) {
    $orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getShippingAddress()));
}

// set payment options
if (count($ccInfo) > 0) {
    $orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
    $cc_number = '4111111111111111';
    $orderObj->getPayment()->setCcNumber($cc_number);
    $orderObj->getPayment()->setCcType('VI');
    $orderObj->getPayment()->setCcExpMonth("12");
    $orderObj->getPayment()->setCcExpYear("2018");
    $orderObj->getPayment()->setCcLast4(substr($cc_number,-4));
    $orderObj->getPayment()->setCcCid('123');
} else {
    $orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
}

$items=$quoteObj->getAllItems();

foreach ($items as $item) {
//@var $item Mage_Sales_Model_Quote_Item
    $orderItem = $convertQuoteObj->itemToOrderItem($item);
    if ($item->getParentItem()) {
        $orderItem->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
    }
    $orderObj->addItem($orderItem);
}

$orderObj->setCanShipPartiallyItem(false);

$totalDue = $orderObj->getTotalDue();

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

try {
    $transaction->save();
} catch (Exception $e){
    Mage::throwException('Order Cancelled Bad Response from Credit Authorization.');
}

$orderObj->sendNewOrderEmail();

Mage::dispatchEvent('checkout_type_onepage_save_order_after', array('order'=>$orderObj, 'quote'=>$quoteObj));

$quoteObj->setIsActive(0);
$quoteObj->save();