Follow by Email

Tuesday, October 21, 2014

Magento Fedex methord not working for India



I have tried to ship with Fedex for India Reagan. And i face some challenges. Then i try to solve it, and i got some solution.
If your origin country is India and you are shipping destination also in India and other country.

For that you have to download RateService_v13.wsdl for fedex
you can get this file from this link

Download it and save it

app\code\core\Mage\Usa\etc\wsdl\FedEx\

Now go to the

app\code\core\Mage\Usa\Model\Shipping\Carrier\Fedex.php

and find

protected function _formRateRequest

Now change function body with

protected function _formRateRequest($purpose)
{
    $r = $this->_rawRequest;
    $ratesRequest = array(
        'WebAuthenticationDetail' => array(
            'UserCredential' => array(
                'Key'      => $r->getKey(),
                'Password' => $r->getPassword()
            )
        ),
        'ClientDetail' => array(
            'AccountNumber' => $r->getAccount(),
            'MeterNumber'   => $r->getMeterNumber()
        ),
        'Version' => $this->getVersionInfo(),
        'RequestedShipment' => array(                                
            'DropoffType'   => $r->getDropoffType(),
            'ShipTimestamp' => date('c'),                   
            'PackagingType' => $r->getPackaging(),
            'Shipper' => array(
                'AccountNumber' => $r->getAccount(),               
                'Address' => array(
                    'PostalCode'  => $r->getOrigPostal(),
                    'CountryCode' => $r->getOrigCountry()
                )
            ),
            'Recipient' => array(
                'AccountNumber' => $r->getAccount(),                 
                'Address' => array(
                    'PostalCode'  => $r->getDestPostal(),
                    'CountryCode' => $r->getDestCountry(),
                    'Residential' => (bool)$this->getConfigData('residence_delivery')
                )
            )
            )
        );

    if($r->getDestCountry()=='IN'){
        $ratesRequest['RequestedShipment']['ServiceType'] = 'STANDARD_OVERNIGHT';
        $ratesRequest['RequestedShipment']['CustomsClearanceDetail'] = array(
                        'DutiesPayment' => array(
                            'PaymentType' => 'SENDER',
                            'Payor' => array(
                                'ResponsibleParty' => array(
                                'AccountNumber' => $r->getAccount(),
                                'Contact' =>array(
                                    'ContactId' => 'sender Contact Id',
                                    'PersonName' => 'Sender Name',
                                    'Title' => 'ABC',
                                    'CompanyName' => 'Sender Company Name',
                                    'PhoneNumber' => '1234567890',
                                    'PhoneExtension' => '91',
                                    'PagerNumber' =>'12', 
                                    'FaxNumber' => '1234567890',
                                    'EMailAddress' => 'mahesh@camstech.com'),
                                'Address' => array('StreetLines' => 'Test Sender Address Line',                                                 
                                                'PostalCode' => $r->getOrigPostal(),
                                                'CountryCode' => $r->getOrigCountry())
                                 )                                          
                                        ),

                            ),
                        'DocumentContent' => 'NON_DOCUMENTS',
                        'CustomsValue' => array('Currency' => 'INR',
                                                'Amount' => '100'),
                        'CommercialInvoice' => array('Purpose' => 'SOLD')

                    );
        $ratesRequest['RequestedShipment']['RequestedPackageLineItems'] = array(
                                'SequenceNumber'=>1,
                                'GroupNumber'=>1,
                                'GroupPackageCount'=>1,
                                'Weight' => array(
                                    'Value' => 1.0,
                                    'Units' => 'KG'
                                ),
                                'Dimensions' => array(
                                    'Length' => 12,
                                    'Width' => 12,
                                    'Height' => 12,
                                    'Units' => 'IN'
                                )
                            );
    }else{
        $ratesRequest['RequestedShipment']['CustomsClearanceDetail'] = array(
                'CustomsValue' => array(
                    'Amount' => $r->getValue(),
                    'Currency' => $this->getCurrencyCode()
                )
            );
        $ratesRequest['RequestedShipment']['TotalInsuredValue'] = array(
                'Amount'  => $r->getValue(),
                'Currency' => $this->getCurrencyCode()
            );
        $ratesRequest['RequestedShipment']['ShippingChargesPayment'] = array(
                'PaymentType' => 'SENDER',
                'Payor' => array(
                    'AccountNumber' => $r->getAccount(),
                    'CountryCode'   => $r->getOrigCountry()
                )
            );
        $ratesRequest['RequestedShipment']['RateRequestTypes'] = 'LIST';
        $ratesRequest['RequestedShipment']['PackageCount']     = '1';
        $ratesRequest['RequestedShipment']['PackageDetail']    = 'INDIVIDUAL_PACKAGES';
        $ratesRequest['RequestedShipment']['RequestedPackageLineItems'] = array(
                '0' => array(
                    'Weight' => array(
                        'Value' => (float)$r->getWeight(),
                        'Units' => $this->getConfigData('unit_of_measure')
                    ),
                    'GroupPackageCount' => 1,
                )
            );               

        if ($purpose == self::RATE_REQUEST_GENERAL) {
            $ratesRequest['RequestedShipment']['RequestedPackageLineItems'][0]['InsuredValue'] = array(
                'Amount'  => $r->getValue(),
                'Currency' => $this->getCurrencyCode()
            );
        } else if ($purpose == self::RATE_REQUEST_SMARTPOST) {
            $ratesRequest['RequestedShipment']['ServiceType'] = self::RATE_REQUEST_SMARTPOST;           
            $ratesRequest['RequestedShipment']['SmartPostDetail'] = array(
                'Indicia' => ((float)$r->getWeight() >= 1) ? 'PARCEL_SELECT' : 'PRESORTED_STANDARD',
                'HubId' => $this->getConfigData('smartpost_hubid')
            );
        }
    }

    return $ratesRequest;
}

Thursday, July 10, 2014

Remove category path from product URL in magento

As great as Magento is there are a number of failings it can have from an search engine optimisation point of view and one of the biggest bugbears our SEO consultants have had with it is the number of different URLs a product can be accessed on.
If product a is in category 1 and two then by default magento will create links to it on the following URLs.
  • www.mystore.com/category-1/product-a.html
  • www.mystore.com/category-2/product-a.html
  • www.mystore.com/product-a.html
This can cause duplicate content issues from a search engine point of view. One solution is ensuring that you have canonical URLs in place so the search engine knows which is the primary URL. Better still is to ensure the same URL is produced for the product each and every time by removing the category part.
The file to edit is /app/code/core/Mage/Catalog/Model/Url.php though i advise rather than editing this directly you create a copy in /app/code/local/Mage/Catalog/Model/Url.php.
Then within function getProductRequestPath (around line 685) amend the following code

/**
     * Prepare product base request path
     */
    /*if ($category->getLevel() > 1) {
        // To ensure, that category has path either from attribute or generated now
        $this->_addCategoryUrlPath($category);
        $categoryUrl = Mage::helper('catalog/category')->getCategoryUrlPath($category->getUrlPath(),
            false, $storeId);
        $requestPath = $categoryUrl . '/' . $urlKey;
    } else {*/
        $requestPath = $urlKey;
    //}

And for good measure also amend the function generatePath to edit around line 831 and comment out this section.

/*if ($category->getLevel() > 1) {
                // To ensure, that category has url path either from attribute or generated now
                $this->_addCategoryUrlPath($category);
                $categoryUrl = Mage::helper('catalog/category')->getCategoryUrlPath($category->getUrlPath(),
                    false, $category->getStoreId());
                return $this->getUnusedPath($category->getStoreId(), $categoryUrl . '/' . $urlKey . $productUrlSuffix,
                    $this->generatePath('id', $product, $category)
                );
            }*/

and around 851 

/*if ($category && $category->getLevel() > 1) {
    return 'catalog/product/view/id/' . $product->getId() . '/category/' . $category->getId();
}*/
 
and around 348
 
/*if ($category->getLevel() > 1) {
            $categoryId = $category->getId();
            $updateKeys = false;
        }*/
 
The next file to edit is /app/code/core/Mage/Catalog/Model/Product/Url.php (again I advise rather than editing this directly you create a copy in /app/code/local) in which we need to ensure the categoryid used for generating the links is always set to null. Edit the function getUrl around line 172 and make the follow amend
 
/* commenting this out and setting the categoryId to null everytime
if (isset($params['_ignore_category'])) {
    unset($params['_ignore_category']);
    $categoryId = null;
} else {
    $categoryId = $product->getCategoryId() && !$product->getDoNotUseCategoryId()
        ? $product->getCategoryId() : null;
}*/
 
$categoryId = NULL;
 
Then hey presto now all the product links in your store should ignore the category path and cut down on canonicalisation issures. I am still in the early days of testing this thus far but have not experienced any problems from it yet.
If you are not comfortable in editing the code yourself then stayed tuned for our all singing all dancing SEO module for magento which will give you greater control over not just this but several other search engine optimisation features of magento.

Wednesday, May 28, 2014

How to get sql query in magento module collection

Suppose we have a data collection and we want to get the sql query running behind it then the following code is the syntax to check it.
$collection = Mage::getModel('catalog/product')->getCollection();
echo $collection->getSelect()->__toString()

How to call a static block in phtml file in magento

We can use a simple code to call a block in any .phtm file. 
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('top_left_links')->toHtml() ?>

How many type of session having in magento?

There have three type of session in magento.
1) Filesystem Session storage
2) Database Session storage
3) Memcached Session storage

 Filesystem Session storage  

To enable file-based storage, choose it during installation or in your app/etc/local.xml file simply make sure you have a session_save tag like this:

<session_save><![CDATA[files]]></session_save>

Database Session storage
 To use the database for session storage simply have this in your local.xml:   
<session_save><![CDATA[db]]></session_save>


Memcached Session storage

Memcached session storage takes a bit more setup than either of the previous two options, which is probably why it’s not considered a ‘normal’ option during Magento install. For starters you need a Memcached server running.

Once you have it up and running, the memcached session storage offers a number of benefits. Firstly it is very cluster friendly. The session data can be shared by any number of webnodes, and to make things even better you can easily add more memcached server nodes so that even your session storage can be scaled to handle many 1000′s of concurrent sessions*. Secondly, it is (or can be) separate of the database and web node entirely, which offloads the work of storing sessions from busy nodes in a high-traffic environment.
To use a memcached session store in Magento you’ll need to have this in your app/etc/local.xml:   
<session_save><![CDATA[memcache]]></session_save>
<session_save_path><![CDATA[tcp://localhost:11211?persistent=1&weight=2&timeout=10&retry_interval=10]]></session_save_path>

Tuesday, May 27, 2014

What is Object Relational Mapping (ORM) php and magento

ORM stands for Object Relational Mapping. It’s a programming technique used to convert different types of data to Objects and vice versa.

In Magento, ORM is shown as Model (based on Zend Framework’s Zend_Db_Adapter), which further breaks down to two types of Models.

  • First is the “simple” i.e. Regular Models which is nothing but flat table or our regular table structure.

  • Second Model is EAV (Entity Attribute Value), which is quite complicated and expensive to query.

 All Magento Models interacting with database are inherited from Mage_Core_Model_Abstract class, which is further inherited from Varien_Object.

Difference between two Models is,  Simple Model is inherited from Mage_Core_Model_Resource_Db_Abstract class,
while EAV is inherited from Mage_Eav_Model_Entity_Abstract.


So, to end up this question, when you want to get some data in Magento, you call it like this: Mage::getModel('module/model')->load(1);

where 1 is the primary key id for some Regular/Simple table, while in EAV so many tables are joined to fetch just single row of data.

Magic function and it's use in magento

As we know in pho 5 they have implemented some magic function which is as follow. 
 __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state() and __clone().

In between that magento is using   __get, __set & __call


Thursday, May 22, 2014

Magento Custom single table extension

Suppose we have a table call "customer_product_like" having field (entity_id, store_id, customer_id, )

Now i want to insert data in this table then the code will be
$connection = Mage::getSingleton('core/resource')->getConnection('core_write');
$fields = array();
$fields['status']= $postData['like'];
$fields['store_id']= Mage::app()->getStore()->getId();
$fields['product_id']= $postData['prodId'];
$fields['customer_id']= $customerId;
$connection->insert('customer_product_like', $fields);

for update
$where = "entity_id = '".$customerProductLikeId."'";
$connection->update('customer_product_like', $fields, $where);

For select
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
 $select = $connection->select()
                    ->from('customer_product_like', array('*'))
                    ->where("product_id = '".$prodId."' AND customer_id = '".$customerId."' AND store_id = '".$storeId."'");
$result = $connection->fetchRow($select);   OR   $result = $connection->fetchAll($select);

Wednesday, May 21, 2014

How to get all available shipping carrier rate by zip code and country code in Magento

If you have country code and zip code then you can find out the all available shipping carrier rate by following code in magento.


$zipcode = '711101';
$country = 'IN';                    
          
$cart = Mage::getSingleton('checkout/cart');
$address = $cart->getQuote()->getShippingAddress();

$address->setCountryId($country)->setPostcode($zipcode)->setCollectShippingrates(true);
$rates = $address->collectShippingRates()->getGroupedAllShippingRates();

foreach ($rates as $carrier) {
             foreach ($carrier as $rate) {
                            print_r($rate->getData());
               }
 }


Saturday, April 19, 2014

How to get innerhtml by id in php

This following code will bring html element inner html by it's id.


$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$html = curl_exec($ch);
curl_close($ch);
$newDom = new domDocument;
libxml_use_internal_errors(true);
$newDom->loadHTML($html);
libxml_use_internal_errors(false);
$newDom->preserveWhiteSpace = false;
$newDom->validateOnParse = true;
     
$sections = $newDom->saveHTML($newDom->getElementById('element id'));  
echo $sections;

Sunday, March 2, 2014

Magento Install Script Will Not Runing

Work your way through <a href="http://alanstorm.com/magento_setup_resources">this article</a> to make sure you don't have any misunderstanding of what the setup resources do, how they work, and how you can troubleshoot them.

Once you've done that, from everything you've said on this question thread it sounds like you're getting your resource "installed", but that your install script never runs. My guess is that the version number you used in

    //0.0.1 is your version number
    mysql4-install-0.0.1.php
   
didn't match up with the version of your module

    <modules>
        <Nie_Nie>
            <version>?.?.?</version>
        </Nie_Nie>
    </modules>
   
Those should match for the script to run.  I **think** Magento is smart enough to run previous versions if it finds them, but the code in the setup resources is the kind that's hard to follow, so I always make sure they match.

Regardless, here's how you can see which file(s) magento is trying to run when it runs your setup resource.  Delete any entries from <code>core_resource</code> related to your module.  Clear your cache.  Then find the following locations in the setup class

    File: app/code/core/Mage/Core/Model/Resource/Setup.php
   
    protected function _modifyResourceDb($actionType, $fromVersion, $toVersion)
    {
        ...   
       
        $sqlFilesDir = Mage::getModuleDir('sql', $modName).DS.$this->_resourceName;       

        if (!is_dir($sqlFilesDir) || !is_readable($sqlFilesDir)) {
            return false;
        }
       
        ...
       
        $sqlDir->close();

        if (empty($arrAvailableFiles)) {
            return false;
        }
       
        ...
       
        $arrModifyFiles = $this->_getModifySqlFiles($actionType, $fromVersion, $toVersion, $arrAvailableFiles);
        if (empty($arrModifyFiles)) {
            return false;
        }
       
and then modify them to add some temporary debugging exceptions       

        if (!is_dir($sqlFilesDir) || !is_readable($sqlFilesDir)) {
            throw new Exception("$sqlFilesDir not found");
            return false;
        }
       
        ...
       
        if (empty($arrAvailableFiles)) {
            throw new Exception("No files found to run");
            return false;
        }
       
        ...

        $arrModifyFiles = $this->_getModifySqlFiles($actionType, $fromVersion, $toVersion, $arrAvailableFiles);
        if (empty($arrModifyFiles)) {
            throw new Exception("No valid upgrade files found to run for ");
            return false;
        }
       
        throw new Exception("If you're getting here, we have a file.  Remove your exceptions here and place one in your installer to make sure it's the one you think it is.");
       
Reload the page and you'll get exception text complaining about whatever Magento can't find.  That should be enough to help you track down which installer script Magento is trying to run, but failing to find. Just remember to delete your module's row in <code>core_resource</code> and to clear your cache. (Magneto caches which modules need to check for an install/upgrade)

If that doesn't work, start digging into the logic of <code>applyAllDataUpdates</code> and figure out why the class isn't including  your installer file.

Monday, February 24, 2014

Reorder via Code in magennto

I have create a extension for reorder please find the following code for it


<?php class Cdotsys_ScheduleOrder_ScheduleorderController extends Mage_Core_Controller_Front_Action{
private $_storeId = '1';
private $_groupId = '1';
private $shipping_methord = 'flatrate_flatrate';
private $_sendConfirmation = '0';
private $orderData = array();
private $_sourceCustomer;

public function IndexAction() {

              $this->loadLayout();   
              $this->getLayout()->getBlock("head")->setTitle($this->__("Scheduleorder"));
                    $breadcrumbs = $this->getLayout()->getBlock("breadcrumbs");
              $breadcrumbs->addCrumb("home", array(
                        "label" => $this->__("Home Page"),
                        "title" => $this->__("Home Page"),
                        "link"  => Mage::getBaseUrl()
                   ));

              $breadcrumbs->addCrumb("scheduleorder", array(
                        "label" => $this->__("Scheduleorder"),
                        "title" => $this->__("Scheduleorder")
                   ));

        $scheduleorders = Mage::getModel('scheduleorder/scheduleorder')->getCollection();    
        foreach($scheduleorders as $scheduleorder){             
            $personsOrder = Mage::getModel('sales/order')->load($scheduleorder->getOrderId());              
            //$personsOrder->setReordered(true);
            $items = $personsOrder->getAllItems();  
            foreach($items as $item){                   
                $products[$item->getProductId()] = array('qty' => $item->getQtyOrdered());                  
            } 
            $this->shipping_methord = $personsOrder->getShippingMethod()
            $customer = Mage::getModel('customer/customer')->load($personsOrder->getCustomerId());
            $this->setOrderInfo($customer,$products);
            $this->create();
            $personsOrder->setPaymentMethod('cashondelivery');

            $order_model = Mage::getSingleton('adminhtml/sales_order_create');
            /*$order_model->setPaymentData('cashondelivery');
            $order_model->getQuote()->getPayment()->addData('cashondelivery');
            $order_model->setShipping('flatrate_flatrate');
            $order_model->getQuote()->getShipping()->addData('flatrate_flatrate');
            $order_model->getQuote()->setShipping(array('method' => 'flatrate_flatrate'));
            $order_model->getQuote()->setPayment(array('method' => 'cashondelivery'));

            $order_model->initFromOrder($personsOrder);             
            $order_model->createOrder();*/
        }

              $this->renderLayout(); 

    }

public function setOrderInfo(Mage_Customer_Model_Customer $sourceCustomer,$products){
        $this->_sourceCustomer = $sourceCustomer;
        //You can extract/refactor this if you have more than one product, etc.
        $Billingaddress = Mage::getModel('customer/address')->load($this->_sourceCustomer->getDefaultBilling());
        $Shippingaddress = Mage::getModel('customer/address')->load($this->_sourceCustomer->getDefaultShipping());
        $this->orderData = array(
        'session'       => array(
                            'customer_id'   => $this->_sourceCustomer->getId(),
                            'store_id'      => $this->_storeId,
                            ),
        'payment'       => array(
                            'method'    => 'checkmo',
                            ),  
        'add_products'  =>$products,
        'order' => array(
                        'currency' => 'USD',
                        'account' => array(
                                'group_id' => $this->_groupId,
                                'email' => $this->_sourceCustomer->getEmail()
                                ),
                        'billing_address' => array(
                                                'customer_address_id' => $this->_sourceCustomer->getDefaultBilling(),
                                                'prefix' => '',
                                                'firstname' => $this->_sourceCustomer->getFirstname(),
                                                'middlename' => '',
                                                'lastname' => $this->_sourceCustomer->getLastname(),
                                                'suffix' => '',
                                                'company' => '',
                                                'street' => array($Billingaddress->getStreet(),''),
                                                'city' => $Billingaddress->getCity(),
                                                'country_id' => $Billingaddress->getCountryId(),
                                                'region' => '',
                                                'region_id' => $Billingaddress->getRegionId(),
                                                'postcode' => $Billingaddress->getPostcode(),
                                                'telephone' => $Billingaddress->getTelephone(),
                                                'fax' => '',
                                                ),
                        'shipping_address' => array(
                                                'customer_address_id' => $this->_sourceCustomer->getDefaultShipping(),
                                                'prefix' => '',
                                                'firstname' => $this->_sourceCustomer->getFirstname(),
                                                'middlename' => '',
                                                'lastname' => $this->_sourceCustomer->getLastname(),
                                                'suffix' => '',
                                                'company' => '',
                                                'street' => array($Shippingaddress->getStreet(),''),
                                                'city' => $Shippingaddress->getCity(),
                                                'country_id' => $Shippingaddress->getCountryId(),
                                                'region' => '',
                                                'region_id' => $Shippingaddress->getRegionId(),
                                                'postcode' => $Shippingaddress->getPostcode(),
                                                'telephone' => $Shippingaddress->getTelephone(),
                                                'fax' => '',
                                                ),
                                                'shipping_method' => $shipping_methord,
                                                'comment' => array(
                                                'customer_note' => 'This order has been created by scheduler order script.',
                                                ),
                            'send_confirmation' => $this->_sendConfirmation
        ),
        );
}   

protected function _getOrderCreateModel()
{
    return Mage::getSingleton('adminhtml/sales_order_create');
}
/**
* Retrieve session object
*
* @return Mage_Adminhtml_Model_Session_Quote
*/
protected function _getSession()
{
    return Mage::getSingleton('adminhtml/session_quote');
}
/**
* Initialize order creation session data
*
* @param array $data
* @return Mage_Adminhtml_Sales_Order_CreateController
*/
protected function _initSession($data)
{
/* Get/identify customer */
    if (!empty($data['customer_id'])) {
        $this->_getSession()->setCustomerId((int) $data['customer_id']);
    }
/* Get/identify store */
    if (!empty($data['store_id'])) {
        $this->_getSession()->setStoreId((int) $data['store_id']);
    }
  return $this;
}

public function create(){
    $orderData = $this->orderData;

    if (!empty($orderData)) {
            $this->_initSession($orderData['session']);
        try {
                $this->_processQuote($orderData);
                if (!empty($orderData['payment'])) {
                    $this->_getOrderCreateModel()->setPaymentData($orderData['payment']);
                    $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($orderData['payment']);
                }

                Mage::app()->getStore()->setConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_ENABLED, "0");
                $_order = $this->_getOrderCreateModel()->importPostData($orderData['order'])->createOrder();
                $this->_getSession()->clear();
                Mage::unregister('rule_data');
                return $_order;
        }
        catch (Exception $e){
            Mage::log("Order save error...");
        }
    }
    return null;
}

protected function _processQuote($data = array()){
    /* Saving order data */
    if (!empty($data['order'])) {
        $this->_getOrderCreateModel()->importPostData($data['order']);
    }
    $this->_getOrderCreateModel()->getBillingAddress();
    $this->_getOrderCreateModel()->setShippingAsBilling(true);
    /* Just like adding products from Magento admin grid */
    if (!empty($data['add_products'])) {
        $this->_getOrderCreateModel()->addProducts($data['add_products']);
    }
    /* Collect shipping rates */
    $this->_getOrderCreateModel()->collectShippingRates();
    /* Add payment data */
    if (!empty($data['payment'])) {
        $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($data['payment']);
    }
    $this->_getOrderCreateModel()->initRuleData()->saveQuote();

    if (!empty($data['payment'])) {
        $this->_getOrderCreateModel()->getQuote()->getPayment()->addData($data['payment']);
    }
    return $this;
}

}


Monday, February 17, 2014

How to send email in Magento and add custom template to it

While creating a local module you may sometimes required to add the send mail functionality on success of your task.
Below is the code and description on how to create a send mail and loading it with a custom template..
 
As my module is based on sending a mail on successfully creating a duplicate order. So I am adding my code in the model folder when the duplicate order is created.

Step1:
At location app/code/local/Namespace/Module/Model/order.php

Add the following code:
//Here I am passing the order object and a payment object as my requirements is to show the product and price details
 public function sendMail(Varien_Object $order, Varien_Object $paymentObj) {

        $email = $order->getCustomerEmail();
        $fName = $order->getCustomerFirstname();
        $lName = $order->getCustomerLastname();

        $customerNote = $order->getCustomerNote();
        $paymentmethod = $paymentObj->getMethod();
      
        try {

            $storeObj = Mage::getModel('core/store')->load($order->getStoreId());
            $customerEmailId = $email;
            $customerFName = $fName;
            $customerLName = $lName;

            //load the custom template to the email 
            $emailTemplate = Mage::getModel('core/email_template')
                    ->loadDefault('custom_template');
           
            // it depends on the template variables
            $emailTemplateVariables = array();
            $emailTemplateVariables['order'] = $order;
            $emailTemplateVariables['store'] = $storeObj;
            $emailTemplateVariables['payment_html'] = $method;
      

            $emailTemplate->setSenderName('Magento');
            $emailTemplate->setSenderEmail('sender.com');
            $emailTemplate->setType('html');
            $emailTemplate->setTemplateSubject('Add a subject');
            $emailTemplate->send($customerEmailId, $customerFName . $customerLName, $emailTemplateVariables);
            return true;
        } catch (Exception $e) {
            $errorMessage = $e->getMessage();
            return $errorMessage;
        }
    }
 
Step2:
At location app/code/local/Namespace/Module/etc/config.xml, add the following block of code
<config>
   <global>
       <template>
            <email>
                <custom_template  module="modulename">
                    <label>any desired  name</label>
                    <file>custom_template.html</file>  // this specifies the path where the custom template is located
                    <type>html</type>
                </custom_template>
            </email>
        </template>
     </global>
</config>
 
Step3:
At location app/locale/template/email/sales
Place your custom template file

Note: If your template file is at location app/locale/template/email, then in your config change the code:         <file>custom_template.html</file>
 

Wednesday, January 29, 2014

Display tier prices at category listing page

$_product->setData('tier_price',null);
$_tierPrices = $this->getTierPrices($_product);

how to get product minimum qty product list page

The following code will help to bring product minimum Qty
<?php echo Mage::getModel("cataloginventory/stock_item")->loadByProduct($_product)->getMinSaleQty();
 ?>

How to run magento store only for USA

Go to System > Configuration > Genera
and change the States Options, Countries Options into your preferable state
it will work..

Thursday, January 23, 2014

Add new field in registration page magento 1.8.1

I have done this with the following steps.
Suppose if you want to add "occupation" after email 
Open template/customer/form/register.phtml and template/customer/form/edit.phtml
 <li>
        <div class="input-box">
            <label for="email_address"><?php echo $this->__('Email Address') ?> <span class="required">*</span></label><br/>
            <input type="text" name="email" id="email_address" value="<?php echo $this->htmlEscape($this->getFormData()->getEmail()) ?>" title="<?php echo $this->__('Email Address') ?>" class="validate-email required-entry input-text" />
        </div>
        <div class="input-box">
            <label for="occupation"><?php echo $this->__('Occupation/Title') ?></label><br/>
            <input type="text" name="occupation" id="occupation" value="<?php echo $this->htmlEscape($this->getFormData()->getOccupation()) ?>" title="<?php echo $this->__('Occupation') ?>" class="input-text" />
        </div>

    </li>


Now open app\code\core\Mage\Customer\etc\config.xml
and add <occupation><create>1</create><update>1</update></occupation>
after <fieldsets><customer_dataflow> 

Now open app\code\core\Mage\Customer\Model\Resource\Setup.php
 find $entities = array(  and add the following code 
'occupation'               => array(
                        'type'               => 'varchar',
                        'label'              => 'Fax',
                        'input'              => 'text',
                        'required'           => false,
                        'sort_order'         => 130,
                        'validate_rules'     => 'a:2:{s:15:"max_text_length";i:255;s:15:"min_text_length";i:1;}',
                        'position'           => 130,
                    ), 

 
Now i insert some value in db

INSERT INTO  `eav_attribute` (
`attribute_id` ,
`entity_type_id` ,
`attribute_code` ,
`attribute_model` ,
`backend_model` ,
`backend_type` ,
`backend_table` ,
`frontend_model` ,
`frontend_input` ,
`frontend_label` ,
`frontend_class` ,
`source_model` ,
`is_required` ,
`is_user_defined` ,
`default_value` ,
`is_unique` ,
`note`
)
VALUES (
NULL '1''school', NULL , NULL 'int', NULL , NULL 'select''School', NULL 'profile/entity_school''1''0''0''0'''
);
- See more at: http://www.excellencemagentoblog.com/customer-registration-fields-magento1-6#sthash.ubBrtvuS.dpuf
INSERT INTO  `eav_attribute` (
`attribute_id` ,
`entity_type_id` ,
`attribute_code` ,
`attribute_model` ,
`backend_model` ,
`backend_type` ,
`backend_table` ,
`frontend_model` ,
`frontend_input` ,
`frontend_label` ,
`frontend_class` ,
`source_model` ,
`is_required` ,
`is_user_defined` ,
`default_value` ,
`is_unique` ,
`note`
)
VALUES (
NULL '1''school', NULL , NULL 'int', NULL , NULL 'select''School', NULL 'profile/entity_school''1''0''0''0'''
);
- See more at: http://www.excellencemagentoblog.com/customer-registration-fields-magento1-6#sthash.ubBrtvuS.dpuf
 INSERT INTO  `eav_attribute` (
`attribute_id` ,
`entity_type_id` ,
`attribute_code` ,
`attribute_model` ,
`backend_model` ,
`backend_type` ,
`backend_table` ,
`frontend_model` ,
`frontend_input` ,
`frontend_label` ,
`frontend_class` ,
`source_model` ,
`is_required` ,
`is_user_defined` ,
`default_value` ,
`is_unique` ,
`note`
)
VALUES (
NULL ,  '1',  'occupation', NULL , NULL ,  'int', NULL , NULL ,  'select',  'School', NULL ,  'profile/entity_school',  '1',  '0',  '0',  '0',  ''
);

INSERT INTO  `eav_entity_attribute` (
`entity_attribute_id` ,
`entity_type_id` ,
`attribute_set_id` ,
`attribute_group_id` ,
`attribute_id` ,
`sort_order`
)
VALUES (
NULL ,  '1',  '1',  '1',  '121',  '0'
);

INSERT INTO  `customer_eav_attribute` (
`attribute_id` ,
`is_visible` ,
`input_filter` ,
`multiline_count` ,
`validate_rules` ,
`is_system` ,
`sort_order` ,
`data_model`
)
VALUES (
'121',  '1', NULL ,  '1', NULL ,  '0',  '0', NULL
);

INSERT INTO `customer_eav_attribute_website` (
`attribute_id` ,
`website_id` ,
`is_visible` ,
`is_required` ,
`default_value` ,
`multiline_count`
)
VALUES (
'121',  '0',  '1',  '0', NULL , NULL
);

INSERT INTO  `customer_form_attribute` (
`form_code` ,
`attribute_id`
)
VALUES (
'adminhtml_customer',  '121'
), (
'checkout_register',  '121'
), (
'customer_account_create',  '121'
), (
'customer_account_edit',  '121'
)
;


Also go to the 
System→Configurations→Customers→Customer Configurations→Address Templates
and Add this code in the “Text” textarea:-
 
{{depend occupation}}{{var occupation}}{{/depend}}

Add this code in the “Html” textarea      
{{depend occupation}}{{var occupation}}<br />{{/depend}}
Add the below code in the “PDF” text area. 
{{depend occupation}}{{var occupation}}|{{/depend}}
 
 

Tuesday, January 21, 2014

Create Left menu in category page

Please open your template\catalog\navigation\left.phtml
 And wright the following code there.

<?php
$current_category = Mage::registry('current_category');
global $current_category_id;
$current_category_id = $current_category->getId();
if($current_category->getLevel()==2){
?>
<div class="block block-layered-nav">
    <div class="block-content">
    <dl id="narrow-by-list2">
            <dt><?php echo $this->__('Category') ?></dt>
            <dd>
               
                    <?php
                    $rootcatId= Mage::app()->getStore()->getRootCategoryId();
                    $categories = Mage::getModel('catalog/category')->getCategories($rootcatId);
                    function  get_categories($categories,$lvl,$c_cat) {   
                        global $current_category_id;
                        $array= '<ul class="level_'.$lvl;
                        if($lvl>1){                           
                            if($current_category_id!=$c_cat){
                                $array .=' cate" style="display:none">';
                            }else{
                                $array .= ' cate open">';
                            }
                        }else{
                            $array .='">';
                        }
                        foreach($categories as $category) {
                            $cat = Mage::getModel('catalog/category')->load($category->getId());
                            $count = $cat->getProductCount();
                            $array .= '<li>';
                           
                            if($cat->getLevel()==2){
                                if($current_category_id!=$category->getId())
                                    $array .='<span class="slide active2"></span>';
                                else
                                    $array .='<span class="slide active1"></span>';
                            }
                           
                            $array .= '<a href="' . Mage::getUrl($cat->getUrlPath()). '">' .
                                      $category->getName() . "(".$count.")</a>\n";
                            if($category->hasChildren()) {
                                $children = Mage::getModel('catalog/category')->getCategories($category->getId());
                                $levl = $category->getLevel();
                                 $array .=  get_categories($children,$levl,$category->getId());
                                }
                             $array .= '</li>';
                        }
                        return  $array . '</ul>';
                    }
                    echo  get_categories($categories,1,$rootcatId);                    
                    ?>
          </dd>         
    </div>               
</div>
<?php } ?>

<script>
var $js = jQuery.noConflict();
$js(document).ready(function() {
    $js('.slide').click(function(){
        $js('.cate').slideUp(300);
        $js('.slide').removeClass('active1');
        $js('.slide').addClass('active2');
       
        $js(this).next().next().slideDown(300);
        $js(this).removeClass('active2');
        $js(this).addClass('active1');
    });
   
});
</script>

Thursday, January 16, 2014

Add Customer group in registration page

If you want to customer can select customer group during registration, then add <group_id><create>1</create></group_id> code into the customer account fieldset.(app\code\core\Mage\Customer\etc\config.xml)

<fieldsets>
<customer_account>
<prefix><create>1</create><update>1</update><name>1</name></prefix>
<firstname><create>1</create><update>1</update><name>1</name></firstname>
<middlename><create>1</create><update>1</update><name>1</name></middlename>
<lastname><create>1</create><update>1</update><name>1</name></lastname>
<suffix><create>1</create><update>1</update><name>1</name></suffix>
<email><create>1</create><update>1</update></email>
<password><create>1</create></password>
<confirmation><create>1</create></confirmation>
<dob><create>1</create><update>1</update></dob>
<taxvat><create>1</create><update>1</update></taxvat>
<group_id><create>1</create></group_id>
</customer_account>
</fieldsets>

Open template/customer/form/register.phtml and add the following code anywhere in the form

<div class="input-box">
<label for="group_id"><?php echo $this->__('Group') ?><span class="required">*</span></label><br/>
<select name="group_id" id="group_id" title="<?php echo $this->__('Group') ?>" class="validate-group required-entry input-text" />
<?php $groups = Mage::helper('customer')->getGroups()->toOptionArray(); ?>
<?php foreach($groups as $group){ ?>
<option value="<?php print $group['value'] ?>"><?php print $group['label'] ?></option>
<?php } ?>
</select>
</div>