Wednesday, August 29, 2012

Magento Events Cheat Sheet Grep – Works for Any Version

Magento Events Cheat Sheet Grep – Works for Any Version

 

If you use the Magento event / observer system for extending Magento (if you don’t you should) then you will find this little script handy for parsing out all of the events in the latest (eg Magento 1.4) version of Magento.
This is a Linux shell script so either use it on your server or if you run a decent desktop OS you should be able to run it on your desktop.
There are two parameters you need to define.



#!/bin/bash
# Find all Magento Events, include file names, line numbers and the preceding 6 lines of code
 
#Please define these two
ABSOLUTE_PATH_TO_MAGENTO_ROOT=/home/joseph/Projects/Magento/
ABSOLUTE_PATH_TO_OUTPUT_FILE_INC_FILE_NAME= /home/joseph/magentoEvents.txt
 
#here is the command
find $ABSOLUTE_PATH_TO_MAGENTO_ROOT  -name "*.php" | xargs -L10 grep -n -B 6 "dispatchEvent" . > $ABSOLUTE_PATH_TO_OUTPUT_FILE_INC_FILE_NAME
 
# save this file as magentoevents.sh
# then do command: chmod +x magentoevents.sh
# then to run, do command: ./magentoevents.sh

Thursday, August 23, 2012

get skin url, get js url, get media url, get store url ,get base url in magneto


These are the following methods to get Magento Base Url, Magento Skin Url, Magento Media Url, Magento Js Url.to get all write the following code

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK); or you can write $this->getUrl();
e.g:- http://yoursite.com/index.php/

Get Magento Media Url
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
e.g:- http://yoursite.com/media/
Get Magento Skin Url

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN); or you can write $this->getSkinUrl();
e.g:- http://yoursite.com/skin/

Get Magento Store Url
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
e.g:- http://yoursite.com/

Get Magento Js Url
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);
http://www.yoursite.com/js

Tuesday, August 21, 2012

Magento: Adding column to sales_flat_order_item, sales_flat_invoice_item and sales_flat_shipment_item

Suppose you want to add column to some table before it gets save in Magento. Example, Magento doesn’t save regular price of product when an order is placed, it only saves the selling price. So if your product have some special price in it, then Magento only saves it’s special price when an order is placed, so there is no track of regular price of that product in order item table. Same it goes to invoice item and shipment item. When creating invoice and shipment, Magento doesn’t have any track on the regular price of invoiced item’s and shipment item’s regular price.
So here I show you how you will add a column “product_mrp” in each of 3 tables and update the information without firing any query!
First of all, make an installer script in your module that will alter these three tables and add column “product_mrp” or any of your choice.
<?php
$installer = $this;
$installer->startSetup();
$installer->run("
    ALTER TABLE sales_flat_order_item ADD COLUMN product_mrp DECIMAL(12,4) NULL;

    ALTER TABLE sales_flat_invoice_item ADD COLUMN product_mrp DECIMAL(12,4) NULL;

    ALTER TABLE sales_flat_shipment_item ADD COLUMN product_mrp DECIMAL(12,4) NULL;
");
$installer->endSetup();
?>
After this is executed, you will find your columns added at the end of your tables.
Now we will catch the event before order is placed, before invoice is created and before shipment is saved.
config.xml

                
                    
                        singleton
Namespace_Module_Model_Observer saveProductMrpInOrder singleton Namespace_Module_Model_Observer saveProductMrpInInvoice singleton Namespace_Module_Model_Observer saveProductMrpInShipment
Now comes the Observer part that will add our column data before data is actually saved in table.
Observer.php
public function saveProductMrpInOrder(Varien_Event_Observer $observer) {
            $order = $observer->getEvent()->getOrder();
            foreach($order->getAllItems() as $item) {
                $price = Mage::getModel('catalog/product')->load($item->getId())->getPrice();
                $item->setProductMrp($price);
            }
          return $this;
        }
        public function saveProductMrpInInvoice(Varien_Event_Observer $observer) {
            $invoice = $observer->getEvent()->getInvoice();
            foreach($invoice->getAllItems() as $item) {
                $price = Mage::getModel('catalog/product')->load($item->getProductId())->getPrice();
                $item->setProductMrp($price);
            }
          return $this;
        }
        public function saveProductMrpInShipment(Varien_Event_Observer $observer)
	{
            $shipment = $observer->getEvent()->getShipment();
            foreach($shipment->getAllItems() as $item) {
                $product = Mage::getModel('catalog/product')->load($item->getProductId());
                $price = $product->getPrice();
                $item->product_mrp = $price;
            }
        }
Now clear the cache, and place order and create it’s invoice and shipment. You will find the regular price of each of your products in all these three useful tables and hence you can track the original price information even if your product’s price has been changed afterwards.

Magento: Linking multiple shipments with their invoices

In Magento, it’s a feature to create multiple invoices and shipments. But you can’t find the link between invoice with their respective shipment if you have more than one invoice and shipment. It’s because if you have forced invoice and shipment enabled (Invoice and Ship button combined in Manage Orders view page), it saves both invoice and shipment object together and hence can’t give the invoice id to shipment and hence fails in building the link between them.
So what we need to do here is:
1. Add a column to sales_flat_shipment which will store invoice increment id (say invoice_id)
2. Before invoice and shipment are saved, get the invoice’s latest increment id and increment it by 1 (to get next invoice increment id)
3. Give that invoice increment id to shipment object, so it will get saved along with other shipment columns
Here we go technically,

Firstly, add a column to sales_flat_shipment table.
<?php
$installer = $this;
$installer->startSetup();
$installer->run("
ALTER TABLE sales_flat_shipment ADD COLUMN invoice_id VARCHAR(50) AFTER increment_id
");
$installer->endSetup();
?>
Then, override InvoiceController.php of sales/order: Mage/Adminhtml/controllers/Sales/Order/InvoiceController.php
Paste this code to newly overridden file:
<?php

require_once('Mage/Adminhtml/controllers/Sales/Order/InvoiceController.php');
class Namespace_Module_Sales_Order_InvoiceController extends Mage_Adminhtml_Sales_Order_InvoiceController
{
    /**
     * @author - Kalpesh Mehta
     * @desc - Rewritten this method for linking shipment and invoice
     */
    public function saveAction()
    {
        $data = $this->getRequest()->getPost('invoice');
        $orderId = $this->getRequest()->getParam('order_id');
        if (!empty($data['comment_text'])) {
            Mage::getSingleton('adminhtml/session')->setCommentText($data['comment_text']);
        }
        try {
            $invoice = $this->_initInvoice();
            if ($invoice) {
                if (!empty($data['capture_case'])) {
                    $invoice->setRequestedCaptureCase($data['capture_case']);
                }
                if (!empty($data['comment_text'])) {
                    $invoice->addComment($data['comment_text'], isset($data['comment_customer_notify']), isset($data['is_visible_on_front']));
                }
                $invoice->register();
                if (!empty($data['send_email'])) {
                    $invoice->setEmailSent(true);
                }
                $invoice->getOrder()->setCustomerNoteNotify(!empty($data['send_email']));
                $invoice->getOrder()->setIsInProcess(true);
                $transactionSave = Mage::getModel('core/resource_transaction')
                    ->addObject($invoice)
                    ->addObject($invoice->getOrder());
                $shipment = false;
                if (!empty($data['do_shipment']) || (int) $invoice->getOrder()->getForcedDoShipmentWithInvoice()) {
                    $shipment = $this->_prepareShipment($invoice);
                    if ($shipment) {
                        //Get last invoice increment ID
                        $invoiceLast = Mage::getModel('sales/order_invoice')->getCollection()
                                ->setOrder('increment_id','DESC')
                                ->setPageSize(1)
                                ->setCurPage(1);
                        $invLastIncrId = $invoiceLast->getFirstItem()->getIncrementId();
                        $invNewIncrId = (int)$invLastIncrId + 1; //incrementing by 1
                        $shipment->setInvoiceId($invNewIncrId); //setting data for our sales_flat_shipment table column invoice_id

                        $shipment->setEmailSent($invoice->getEmailSent());
                        $transactionSave->addObject($shipment);
                    }
                }
                $transactionSave->save();
                if (!empty($data['do_shipment']) || (int) $invoice->getOrder()->getForcedDoShipmentWithInvoice()) {
                    $this->_getSession()->addSuccess($this->__('The invoice and shipment have been created.'));
                } else {
                    $this->_getSession()->addSuccess($this->__('The invoice has been created.'));
                }
                // send invoice/shipment emails
                $comment = '';
                if (isset($data['comment_customer_notify'])) {
                    $comment = $data['comment_text'];
                }
                try {
                    $invoice->sendEmail(!empty($data['send_email']), $comment);
                } catch (Exception $e) {
                    Mage::logException($e);
                    $this->_getSession()->addError($this->__('Unable to send the invoice email.'));
                }
                if ($shipment) {
                    try {
                        $shipment->sendEmail(!empty($data['send_email']));
                    } catch (Exception $e) {
                        Mage::logException($e);
                        $this->_getSession()->addError($this->__('Unable to send the shipment email.'));
                    }
                }
                Mage::getSingleton('adminhtml/session')->getCommentText(true);
                $this->_redirect('*/sales_order/view', array('order_id' => $orderId));
            } else {
                $this->_redirect('*/*/new', array('order_id' => $orderId));
            }
            return;
        } catch (Mage_Core_Exception $e) {
            $this->_getSession()->addError($e->getMessage());
        } catch (Exception $e) {
            $this->_getSession()->addError($this->__('Unable to save the invoice.'));
            Mage::logException($e);
        }
        $this->_redirect('*/*/new', array('order_id' => $orderId));
    }
}