Pages

Tuesday, August 6, 2013

Get Store Email address in Magento

//General Contact
echo $name = Mage::getStoreConfig('trans_email/ident_general/name'); //sender name
echo $email = Mage::getStoreConfig('trans_email/ident_general/email'); //sender email
//Sales Representative
echo $name = Mage::getStoreConfig('trans_email/ident_sales/name'); //sender name
echo $email = Mage::getStoreConfig('trans_email/ident_sales/email'); //sender email
//Customer Support
echo $name = Mage::getStoreConfig('trans_email/ident_support/name'); //sender name
echo $email = Mage::getStoreConfig('trans_email/ident_support/email'); //sender email
 //Custom Email 1
echo $name = Mage::getStoreConfig('trans_email/ident_custom1/name'); //sender name
echo $email = Mage::getStoreConfig('trans_email/ident_custom1/email'); //sender email
//Custom Email 2
echo $name = Mage::getStoreConfig('trans_email/ident_custom2/name'); //sender name
echo $email = Mage::getStoreConfig('trans_email/ident_custom2/email'); //sender email

Track visitors information in magento

Here, I will show you how to track visitor’s data information in Magento. By visitor’s information, I mean information like remote address, http host, user agent (browser), referer url, first visit date time, last visit date time, etc.
The following code fetches the vistor data:-
$visitorData = Mage::getSingleton('core/session')->getVisitorData();
// printing visitor information data
echo "<pre>"; print_r($visitorData); echo "</pre>";
You will get an array of visitor information data like the following one:-

Array
(
    [] =>
    [server_addr] => 167772437
    [remote_addr] => 167772437
    [http_secure] =>
    [http_host] => 127.0.0.1
    [http_user_agent] => Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.237 Safari/534.10
    [http_accept_language] => en-US,en;q=0.8
    [http_accept_charset] => ISO-8859-1,utf-8;q=0.7,*;q=0.3
    [request_uri] => /magento/index.php/catalog/category/view/id/22
    [session_id] => 13qm5u80238vb15lupqcac97r5
    [http_referer] => http://127.0.0.1/magento/
    [first_visit_at] => 2011-01-17 11:42:23
    [is_new_visitor] =>
    [last_visit_at] => 2011-01-17 11:58:38
    [visitor_id] => 41
    [last_url_id] => 139
)

In the above array, the server_addr and remote_addr are in different form than usual. The (IPv4) Internet Protocol dotted address has been converted into a proper address using ip2long PHP function. You can get the same kind of value from the following code:-
// user's ip address (visitor's ip address)
$remoteAddr = Mage::helper('core/http')->getRemoteAddr(true);
// server's ip address (where the current script is)
$serverAddr = Mage::helper('core/http')->getServerAddr(true);

Hope this helps. Thanks.

How to get the customer login, logout, register and checkout url in magento

Mage::getUrl(‘customer/account/login’); //login url
Mage::getUrl(‘customer/account/logout’); //logout url
Mage::getUrl(‘customer/account’); //My Account url
Mage::getUrl(‘customer/account/create’); // Register url
Mage::getUrl(‘checkout/cart’); //Checkout url

Remove or rename ‘Add New’ button from Admin Grid Magento

Rename ‘Add New’ button

Here are the steps to rename the ‘Add New’ text to anything you required (for example, ‘Add Report’):-
- Go to YourNamespace -> YourModule -> Block -> Adminhtml -> YourFile.php
- Add the following code in the constructor of this file:-

$this->_addButtonLabel = Mage::helper('yourmodulename')->__('Add Report');


Remove ‘Add New’ button

Here are the steps to remove the ‘Add New’ button:-
- Go to YourNamespace -> YourModule -> Block -> Adminhtml -> YourFile.php
- Add the following code in the constructor of this file (it should be just below the call to parent constructor):-

parent::__construct();
$this->_removeButton('add');

Thursday, August 1, 2013

Script to export magento categories

If you are after a quick method to get all the category ID’s for your categories for some Excel lookups (for new data imports), then this quick PHP script should help you out:

<?php

    define('MAGENTO', realpath(dirname(__FILE__)));
    require_once MAGENTO . '/app/Mage.php';
    Mage::app();

    $category = Mage::getModel ( 'catalog/category' );
    $tree = $category->getTreeModel ();
    $tree->load ();
    
    $ids = $tree->getCollection ()->getAllIds ();
    
    if ($ids) {
        $file = "var/import/catwithid.csv";
        file_put_contents($file,"catId, catNamen");
        foreach ( $ids as $id ) {
          $string = $id . ', ' .$category->load($id)->getName() . "n";
            file_put_contents($file,$string,FILE_APPEND);
        }
    }
?>

Generate Category Tree in Magento

<?php
$rootDir = ""; //include root path
include($rootDir."app/Mage.php");
$rootcatId= Mage::app()->getStore()->getRootCategoryId();
$categories = Mage::getModel('catalog/category')->getCategories($rootcatId);
function  get_categories($categories) {
    $array= '<ul>';
    foreach($categories as $category) {
        $cat = Mage::getModel('catalog/category')->load($category->getId());
        $count = $cat->getProductCount();
        $array .= '<li>'.
        '<a href="' . Mage::getUrl($cat->getUrlPath()). '">' .
                  $category->getName() . "(".$count.")</a>\n";
        if($category->hasChildren()) {
            $children = Mage::getModel('catalog/category')->getCategories($category->getId());
             $array .=  get_categories($children);
            }
         $array .= '</li>';
    }
    return  $array . '</ul>';
}
echo  get_categories($categories); ?>

Monday, July 29, 2013

How to create Credit Memo programmatically in magento

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();

How to create Shipment programmatically in magento

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);
}

How to create invoice programmatically in magento

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) {
 
}

How to create customer programmatically in magento

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

$customer = Mage::getModel('customer/customer');
$password = 'test1234';
$email = 'dtest@gmail.com<script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName("script");l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>';
$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();
}