Showing posts with label Magento. Show all posts
Showing posts with label Magento. Show all posts

Saturday 4 November 2017

How to Rewrite / Override block in magento

How to Rewrite / Override block in magento

Here we are Overriding / Rewriting magento block of Mage_Catalog_Block_Product_View with custom module named Chand_Software.

(1) Create module file in app/etc/modules/Chand_Software.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Chand_Software>
            <active>true</active>
            <codePool>local</codePool>
        </Chand_Software>
    </modules>
</config>

(2) Create module config file in app/code/local/Chand/Software/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Chand_Software>
            <version>1.0.0</version>
        </Chand_Software>
    </modules>
    <global>
        <blocks>
            <catalog>  // This is the block identifier which we want rewrite
                <rewrite>
                    <product_view>Chand_Software_Block_Product_View</product_view>
                </rewrite>
            </catalog>
        </blocks>
    </global>
</config>

(3) Now Create block file of our custom module in app/code/local/Chand/Software/Block/Product/View.php

class Chand_Software_Block_Product_View extends Mage_Catalog_Block_Product_View
{
    /**
     * Put your logic here
     *
     */
}

How to add css in only product type simple in magento

How to add css in only product type simple in magento

First to create local.xml file at this path app/design/frontend/yourpackage/default/layout/local.xml and paste below code in local.xml

<?xml version="1.0"?>

<layout version="0.1.0">

    <PRODUCT_TYPE_simple>
   
            <reference name="head">
   
                <action method="addCss"><stylesheet>css/your_simple.css</stylesheet></action>
   
            </reference>
   
    </PRODUCT_TYPE_simple>

</layout>

Handle of different product types :

<PRODUCT_TYPE_simple>
<PRODUCT_TYPE_configurable>
<PRODUCT_TYPE_grouped>
<PRODUCT_TYPE_virtual>
<PRODUCT_TYPE_downloadable>
<PRODUCT_TYPE_bundle>

Monday 12 December 2016

How to add sku column in sales order grid magento admin


How to add sku column in sales order grid magento admin

Note: For not to override magento core functionality, You can create your own module and use the below code in Grid.php

Open app\code\core\Mage\Adminhtml\Block\Sales\Order\Grid.php

Replace the below function

protected function _prepareCollection()
{
    $collection = Mage::getResourceModel($this->_getCollectionClass());
    $collection->getSelect()->joinLeft(
            'sales_flat_order_item',
            '`sales_flat_order_item`.order_id=`main_table`.entity_id',
            array('skus'  => new Zend_Db_Expr('group_concat(`sales_flat_order_item`.sku SEPARATOR ",")'))
    );
    $collection->getSelect()->group('entity_id');
   
    $this->setCollection($collection);
    return parent::_prepareCollection();
}

Now put the below code in _prepareColumns() function

$this->addColumn('sku', array(
    'header' => Mage::helper('sales')->__('SKU'),
    'index' => 'skus',
    'type' => 'text',
    'width' => '100px',
    'filter'    => false,
));

Wednesday 30 November 2016

How to enable paypal payment standard in magento 1.9.2.1


How to enable paypal payment standard in magento 1.9.2.1

In magento 1.9.2.1 Paypal Payment Standard method not exist. If you want use paypal, you have to select Website Payments Standard (Includes Express Checkout). Here i have used small trick to reuse the old method.

Run the following query in your database and check in admin panel in payment method section

update core_config_data set value = '1' where path = 'payment/paypal_standard/active';

Wednesday 9 November 2016

PayPal gateway has rejected request. Currency is not supported paypal Express error magento



PayPal gateway has rejected request. Currency is not supported paypal Express error magento

Generally People face this type error becoz of Paypal does not support requested currency. For Example : If you are trying to checkout with Indian Rupee , You would get this type of error due to paypal does not support Indian Rupee. In this condition you have to switch the your base currency to paypal supported currency. But with this solution your store price will be changed. so that here i came with small hack.

I have used small trick to rid this error. It is not good solution but sometime it is useful.

Go to app\code\core\Mage\Paypal\Model\Express\Checkout.php. Find the public function start and find below code

$this->_api->setAmount($this->_quote->getBaseGrandTotal())
            ->setCurrencyCode($this->_quote->getBaseCurrencyCode())
            ->setInvNum($this->_quote->getReservedOrderId())
            ->setReturnUrl($returnUrl)
            ->setCancelUrl($cancelUrl)
            ->setSolutionType($solutionType)
            ->setPaymentAction($this->_config->paymentAction);

Just replace the below code

$this->_api->setAmount($this->_quote->getBaseGrandTotal())
            ->setCurrencyCode('USD')
            ->setInvNum($this->_quote->getReservedOrderId())
            ->setReturnUrl($returnUrl)
            ->setCancelUrl($cancelUrl)
            ->setSolutionType($solutionType)
            ->setPaymentAction($this->_config->paymentAction);

With this trick now you will go to paypal without any error. But you have to convert the price from Base Currency to USD.

Note: This solution is only for Paypal Express Users.

That's it. Enjoy Chandresh Rana's Coding...

How to make custom mini shopping cart in header magento

How to make custom mini shopping cart in header magento

Kindly Copy the below code and paste it into your header.phtml file.

<div class="shopping_cart active">
<?php $cart = Mage::getModel('checkout/cart')->getQuote(); ?>
    <?php $cnt = Mage::helper('checkout/cart')->getSummaryCount(); ?>
    <div class="icon">
        <i class="shopping-bag-icon v-middle"></i>
        <span class="count-number"><?php if($cnt > 0){echo $cnt;}else{echo "0";} ?></span>
    </div>
    <span class="block-cart hidden-xs hidden-sm">
        <b class="hidden-xs hidden-sm m-l-sm">MY BAG</b>
        <p>item(s)</p>
    </span>
    <?php if($cnt > 0): ?>
        <div class="cart_block cart-block exclusive">
            <div class="block_content">
                <p class="cart-subtitle">Recently added item(s)</p>
                <div class="cart_block_list">
                    <div class="products">
                        <?php foreach ($cart->getAllVisibleItems() as $item): ?>
                                <?php $_product = Mage::getModel('catalog/product')->load($item->getProduct()->getId()); ?>
                                <div class="product-item-list">
                                    <a href="<?php echo $_product->getProductUrl() ?>" class="cart-images">
                                        <img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame(false)->resize(72, 99); ?>" class="img-responsive"></a>
                                    <div class="cart-info">
                                        <div class="product-name">
                                            <a href="<?php echo $_product->getProductUrl() ?>" class="cart_block_product_name"><?php echo $_product->getName(); ?></a>
                                        </div>
                                        <span><?php echo $item->getQty(); ?>  x </span>
                                        <span class="price"><?php echo Mage::helper('core')->currency($_product->getFinalPrice(), 2); ?> </span>
                                    </div>
                                    <span class="remove_link">
                                           <a href="<?php echo $this->getUrl('checkout/cart/delete',array('id'=>$item->getId(),Mage_Core_Controller_Front_Action::PARAM_NAME_URL_ENCODED => $this->helper('core/url')->getEncodedUrl())); ?>" rel="nofollow" title="remove this product from my cart"><i class="delet-item"></i>
                                            </a>
                                     </span>
                                </div>
                        <?php endforeach; ?>      
                    </div>
                </div>
            </div>
           
            <div class="clearfix"></div>
            <div class="buttons  m-t-sm">
                <div class="row">
                    <div class="col-xs-6 p-r-xs">
                        <button onclick="setLocation('<?php echo $this->getUrl('checkout/cart'); ?>')" type="button" title="View Bag" class="btn btn-theme btn-block"><span>VIEW BAG</span> </button>
                    </div>
                    <div class="col-xs-6 p-l-xs">
                        <button onclick="setLocation('<?php echo $this->getUrl('onepagecheckout'); ?>')" class="btn brown-btn  btn-block" title="Checkout" type="button"><span>CHECKOUT</span> </button>
                    </div>  
                </div>  
            </div>

        </div>

    <?php endif; ?>
</div>

Tuesday 8 November 2016

How to set validation on checkout with minimum qty purchase magento



How to set validation on checkout with minimum qty magento

Put below code in your module/any module config.xml file after <models> block
<global>
    <events>
        <controller_action_predispatch_checkout_onepage_index>
            <observers>
                <spirit_cms_validate_checkout>
                    <class>Setblue_Banner_Model_Observer</class>
                    <method>validateCheckout</method>
                </spirit_cms_validate_checkout>
            </observers>
        </controller_action_predispatch_checkout_onepage_index>
    </events>
</global>

Next we need to create observer file to read this code. Create Observer.php in /yourmodule/Model/Observer.php and put the below code :

public function validateCheckout($observer)
{
    // Ensure we only observe once. $oObserver
    if( Mage::registry( 'restrict_checkout_flag' ) )
    {
        return $this;
    }
    else
    {
        $oQuote = Mage::getSingleton( 'checkout/cart' )->getQuote();
        $oCartItems = $oQuote->getAllItems();
        $iTotalAmount = $oQuote->getGrandTotal();
        $iGroupId = $oQuote->getCustomerGroupId();
        $iTotalQty = 0;
        foreach( $oCartItems as $oCartItem )
        {
            $iTotalQty = $iTotalQty + $oCartItem->getQty();
        }
        if($iGroupId == '2'){
            if( $iTotalQty < 15 )
            {
                $oSession = Mage::getSingleton( 'checkout/session' );
                $oSession->addError( 'Please add at least 15 items to your cart.' );
                Mage::app()->getResponse()->setRedirect( Mage::getUrl( 'checkout/cart' ) );
            }
            Mage::register( 'restrict_checkout_flag', 1, TRUE );
        }
     
    }
}

Monday 17 October 2016

Register Customer approve by admin for wholesale user group magento


Register Customer approve by admin for wholesale user group magento

To Enable the Require Emails Confirmation, Go to system->configuration->Customer configuration open Create New Account Options section


Open register.phtml and put the below line before the submit button for assign wholesale group.

<input type="hidden" name="group_id" id="group_id" value="2" />

Now open \app\code\core\Mage\Customer\controllers\AccountController.php

Change $message variable like below in loginPostAction() function

$message = $this->_getHelper('customer')->__('This account is not approved. You will receive an email with confirmation once your account is approved by admin.');

Change in createPostAction() function

Find $errUrl = $this->_getUrl('*/*/login', array('_secure' => true));

and replace as below

    if($this->getRequest()->getPost('group_id') == 2){
        $errUrl = $this->_getUrl('*/*/create?register=wholesale', array('_secure' => true));
    }else{
        $errUrl = $this->_getUrl('*/*/login', array('_secure' => true));
    }

Now Replace _successProcessRegistration() function as below  
   
    protected function _successProcessRegistration(Mage_Customer_Model_Customer $customer)
    {
        $session = $this->_getSession();
/* Code By Chand */
        if ($customer->isConfirmationRequired() && $this->getRequest()->getPost('group_id') == 2) {
            /** @var $app Mage_Core_Model_App */
            $app = $this->_getApp();
            /** @var $store  Mage_Core_Model_Store*/
            $store = $app->getStore();
            $customer->sendNewAccountEmail(
                'confirmation',
                $session->getBeforeAuthUrl(),
                $store->getId()
            );
            $customerHelper = $this->_getHelper('customer');
            $session->addSuccess($this->__('Thank you for registering with us. Your account is under moderation and will be approved by admin soon.',
/* End Code By Chand */  
                $customerHelper->getEmailConfirmationUrl($customer->getEmail())));
            $url = $this->_getUrl('*/*/index', array('_secure' => true));
        } else {
            $session->setCustomerAsLoggedIn($customer);
            $url = $this->_welcomeCustomer($customer);
        }
        $this->_redirectSuccess($url);
        return $this;
    }

In _getCustomer() function replace line $customer->getGroupId(); as below

if($this->getRequest()->getPost('group_id')){
       $customer->setGroupId($this->getRequest()->getPost('group_id'));
}else{
$customer->getGroupId();
}


Now open \app\code\core\Mage\Customer\Model\Customer.php and replace isConfirmationRequired() function as below

    public function isConfirmationRequired()
    {
        if ($this->canSkipConfirmation()) {
            return false;
        }
/* Code By Chand */
        if (self::$_isConfirmationRequired === null && $this->getGroupId() == 2) {
            $storeId = $this->getStoreId() ? $this->getStoreId() : null;
            self::$_isConfirmationRequired = (bool)Mage::getStoreConfig(self::XML_PATH_IS_CONFIRM, $storeId);
        }
/* End Code By Chand */
        return self::$_isConfirmationRequired;
    }


Go to magento admin panel open transactional Emails in system. Open New account confirmation key template and paste below code:

    {{template config_path="design/email/header"}}
    {{inlinecss file="email-inline.css"}}
   
    <table cellpadding="0" cellspacing="0" border="0">
        <tr>
            <td>
                <table cellpadding="0" cellspacing="0" border="0">
                    <tr>
                        <td class="action-content">
                            <h1>{{htmlescape var=$customer.name}},</h1>
                            <p>Thank you for registering with us. Your account is under moderation and will be approved by admin soon.</p>
                            <p class="highlighted-text">
                                Use the following values when prompted to log in:<br/>
                                <strong>Email:</strong> {{var customer.email}}<br/>
                                <strong>Password:</strong> {{htmlescape var=$customer.password}}
                            </p>
                            <p>
                                If you have any questions, please feel free to contact us at
                                <a href="mailto:{{var store_email}}">{{var store_email}}</a>
                                {{depend store_phone}} or by phone at <a href="tel:{{var phone}}">{{var store_phone}}</a>{{/depend}}.
                            </p>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
   
    {{template config_path="design/email/footer"}}


Open New account confirmed template and paste below code:

    {{template config_path="design/email/header"}}
    {{inlinecss file="email-inline.css"}}
   
    <table cellpadding="0" cellspacing="0" border="0">
        <tr>
            <td class="action-content">
                <h1>{{htmlescape var=$customer.name}},</h1>
                <p>Congratulations. Your account has been approved. Now you can access our wholesale catalog price.</p>
                <p>To log in when visiting our site just click <a href="{{store url="customer/account/"}}">Login</a> or <a href="{{store url="customer/account/"}}">My Account</a> at the top of every page, and then enter your email address and password.</p>
                <p>When you log in to your account, you will be able to do the following:</p>
                <ul>
                    <li>Proceed through checkout faster when making a purchase</li>
                    <li>Check the status of orders</li>
                    <li>View past orders</li>
                    <li>Make changes to your account information</li>
                    <li>Change your password</li>
                    <li>Store alternative addresses (for shipping to multiple family members and friends!)</li>
                </ul>
                <p>
                    If you have any questions, please feel free to contact us at
                    <a href="mailto:{{var store_email}}">{{var store_email}}</a>
                    {{depend store_phone}} or by phone at <a href="tel:{{var phone}}">{{var store_phone}}</a>{{/depend}}.
                </p>
            </td>
        </tr>
    </table>
   
    {{template config_path="design/email/footer"}}

Assigned both template from Customer configuration in magento admin panel.


Thursday 29 September 2016

Sales report shows wrong invoiced amount in magento


Sales report shows wrong invoiced amount in magento

Most of people have this issue.

The solution is that refresh the lifetime statistic instead of the daily statistic refresh.

Moreover refer the below picture for more information about the current report.


Monday 26 September 2016

Change contact email template plain text to HTML format magento


Change contact email template plain text to HTML format magento

Open app/code/core/Mage/Contacts/etc/config.xml

Note: You can create your own module and override the contact module config.xml file.

<email>
   <contacts_email_email_template translate="label" module="contacts">
       <label>Contact Form</label>
       <file>contact_form.html</file>
       <type>text</type>
   </contacts_email_email_template>
</email>

Replace to

<email>
   <contacts_email_email_template translate="label" module="contacts">
       <label>Contact Form</label>
       <file>contact_form.html</file>
       <type>html</type>
   </contacts_email_email_template>
</email>

Tuesday 6 September 2016

Insert product in magento through Soap API with media images


Insert product in magento through Soap API with media images

<?php
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
error_reporting(E_ALL);
ini_set('display_errors', 1);

//create soap object
$mage_url = 'http://cohodeals.com/index.php/api/soap?wsdl';
$mage_user = 'chandresh';
$mage_api_key = '12345678';
// Initialize the SOAP client
$soap = new SoapClient($mage_url);

// Login to Magento
$session_id = $soap->login($mage_user, $mage_api_key);
$productData = array(
    'name' => $_REQUEST['name'], //'Test product'
'categories' => array($_REQUEST['cat']),
    'websites' => array(1),
    'short_description' => $_REQUEST['desc'],
    'description' => $_REQUEST['desc'],
    'price' => $_REQUEST['price'],
    'status' => 1,
    'tax_class_id' => 0,
    'url_key' => $_REQUEST['url'],
    'visibility' => '4',
'stock_data' => array(
'qty' => $_REQUEST['qty'],
'is_in_stock' => 1
    )
);
$sku = $_REQUEST['sku'];
$storeView = 1;
$attributeSetId = 4; // you can get this id from admin area
$productType = 'simple';
try {

$product_exist = null;
try{
 $product_exist = $soap->call($session_id, 'product.info', $sku);
 }
 catch(exception $e){
 //nothing to do
}
 
if($product_exist==null or  $product_exist==""){
$result = $soap->call($session_id, 'catalog_product.create', array($productType, $attributeSetId, $sku, $productData, $storeView));

/* Image Upload area start */

//Get the file
$url = $_REQUEST['image'];
$content = file_get_contents($url);

//Store in media.
$imageInfo = pathinfo($url);
$imageName = $imageInfo['basename'];
$fp = fopen("../media/import/".$imageName, "w");
fwrite($fp, $content);
fclose($fp);

//attach image with database
require_once '../app/Mage.php';
Mage::app();
$path = Mage::getBaseDir('media') . DS . 'import' . DS . $imageName;
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = base64_encode($data);
$productId = $result;
$file = array(
'content' => $base64,
'mime' => 'image/jpeg'
);
$result = $soap->call(
$session_id,
'catalog_product_attribute_media.create',
array(
$productId,
array('file'=>$file, 'label'=>'Label', 'position'=>'1', 'types'=>array('thumbnail','small_image','image'), 'exclude'=>0)
)
);
/* Image Upload area end */


}
else {
  //$result = $soap->call($session_id, 'catalog_product.delete', $sku);
  $result = $soap->call($session_id, 'catalog_product.update', array($sku,$productData));
}

   

echo 'Product Uploaded Successfully';
} catch (SoapFault $e) {
    echo "Error in inserting product with sku $sku : " . $e->getMessage();
}

Sunday 21 August 2016

Display image column in manage category grid magento admin


Display image column in manage category grid magento admin


Here i will show you how to create image column in admin mangage category grid magento.

First open app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/Product.php file.

You can copy this file in your local folder so that magento core functionality will not be override.

Put the below code in _prepareColumns() function to create image column in grid.

    $this->addColumn('image', array(
        'header' => Mage::helper('catalog')->__('Image'),
        'align' => 'left',
        'index' => 'image',
        'width'     => '100',
        'renderer'  => 'adminhtml/Catalog_Category_Grid_Render_Image',
    ));

You can check in code we have created renderer to fetch product image. Now as per renderer create the Grid folder then Render folder and then Image.php file in app/code/core/Mage/Adminhtml/Block/Catalog/Category/ folder

Copy and paste the below code in Image.php file

class Mage_Adminhtml_Block_Catalog_Category_Grid_Render_Image extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
    public function render(Varien_Object $row)
{
$products = Mage::getModel('catalog/product')->load($row->getEntityId());
try{
  $imgSrc = Mage::helper('catalog/image')->init($products, 'small_image')->resize(100);
}
catch(Exception $e) {
  $imgSrc = Mage::getDesign()->getSkinUrl('images/catalog/product/placeholder/image.jpg',array('_area'=>'frontend'));
}
return '<img src="'.$imgSrc.'" alt="'.$strBannerTitle.'" title="'.$strBannerTitle.'" width="100px">';
    }
}

Now you can check in admin panel image shows in image column like below:

Tuesday 16 August 2016

Add Sku column in products ordered report grid magento


Add Sku column in products ordered report grid magento

Kindly open app\code\core\Mage\Adminhtml\Block\Report\Product\Sold\Grid.php and put the below code in _prepareColumns() function

You can move Grid.php in your local folder as well.

$this->addColumn('sku', array(
    'header'    => Mage::helper('reports')->__('Product Sku'),
    'index'     =>'sku'
));



That's it. Enjoy Chandresh Rana's Coding...

Wednesday 10 August 2016

How to add product in wishlist with custom options magento


How to add product in wishlist with custom options magento

After a few hour debugging i got the solution about How to add custom option in wishlist. By default Magento has no functionality to add custom option with product in wishlist. Kindly follow the below steps to add product in wishlist with custom option.

Open app/design/frontend/default/yourtheme/template/catalog/product/view.phtml

Remove the default Add to wishlist button and replace the below one

<?php $_wishlistSubmitUrl = $this->helper('wishlist')->getAddUrl($_product); ?>
<span onclick="wishlistWithOption('<?php echo $_wishlistSubmitUrl; ?>');" style="cursor:pointer"><i class="pd-wishlist"></i>Add to Wishlist</span>

After this code put the below javascript function

<script type="text/javascript">
function wishlistWithOption(url){
var sel = jQuery('select').attr("id");
if(sel){
var selId = sel.split('_');
setLocation(url+selId[1]+'/'+jQuery('#'+sel).val());
}else{
setLocation(url);
}
}
</script>

Now open the app/code/core/Mage/Wishlist/controllers/IndexController.php file. you can also create Observer for this functionlity.

Add the below code in _addItemToWishList() function. After the $requestParams = $this->getRequest()->getParams(); line.

$i = 1;
foreach($requestParams as $key=> $_requestParams){
    if($i == 3){
        $requestParams = array(
            'product' => $productId,
            'store_id' => $storeId,
            'qty' => 1,
            'options' => array($key=>$_requestParams)
        );
    }
    $i++;
}

Note : The above code works only that products which have select(Dropdown) custom option like Size, Color..

That's it. Enjoy Chandresh Rana Coding..


Monday 8 August 2016

How to send cancel order email to customer magento


How to send cancel order email to customer magento

(1) First create template html file order_cancel.html like below and put it at app/locale/en_US/template/email/sales/


    <!--@subject {{var store.getFrontendName()}}: Your Order # {{var order.increment_id}} was received, but failed @-->
    <!--@vars
    {"store url=\"\"":"Store Url",
    "var logo_url":"Email Logo Image Url",
    "var logo_alt":"Email Logo Image Alt",
    "htmlescape var=$order.getCustomerName()":"Customer Name",
    "var store.getFrontendName()":"Store Name",
    "store url=\"customer/account/\"":"Customer Account Url",
    "var order.increment_id":"Order Id",
    "var order.getCreatedAtFormated('long')":"Order Created At (datetime)",
    "var order.getBillingAddress().format('html')":"Billing Address",
    "var payment_html":"Payment Details",
    "var order.getShippingAddress().format('html')":"Shipping Address",
    "var order.getShippingDescription()":"Shipping Description",
    "layout handle=\"sales_email_order_items\" order=$order":"Order Items Grid",
    "var order.getEmailCustomerNote()":"Email Order Note"}
    @-->
    <!--@styles
    @-->
 
    {{template config_path="design/email/header"}}
    {{inlinecss file="email-inline.css"}}
 
    <table cellpadding="0" cellspacing="0" border="0">
        <tr>
            <td>
                <table cellpadding="0" cellspacing="0" border="0">
                    <tr>
                        <td class="email-heading">
                            <h1>Dear {{var customer_name}}, Thank you for choosing {{var store.getFrontendName()}}.</h1>
                            <p class="new-order-tag">Greetings from {{var store.getFrontendName()}},
    We saw that you were about to shop for some products from our store and you didn't get a chance to finish your order (Order ID : # {{var order.increment_id}}) for some reason. </p>
                        </td>
                        <td class="store-info">
                            <h4>Order Questions?</h4>
                            <p>
                                {{depend store_phone}}
                                <b>Call Us:</b>
                                <a href="tel:{{var phone}}">{{var store_phone}}</a><br>
                                {{/depend}}
                                {{depend store_hours}}
                                <span class="no-link">{{var store_hours}}</span><br>
                                {{/depend}}
                                {{depend store_email}}
                                <b>Email:</b> <a href="mailto:{{var store_email}}">{{var store_email}}</a>
                                {{/depend}}
                            </p>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td class="order-details">
                <h3>Your order <span class="no-link">#{{var order.increment_id}}</span></h3>
                <p>Placed on {{var order.getCreatedAtFormated('long')}}</p>
            </td>
        </tr>
        <tr class="order-information">
            <td>
                {{if order.getEmailCustomerNote()}}
                <table cellspacing="0" cellpadding="0" class="message-container">
                    <tr>
                        <td>{{var order.getEmailCustomerNote()}}</td>
                    </tr>
                </table>
                {{/if}}
                {{layout handle="sales_email_order_items" order=$order}}
                <table cellpadding="0" cellspacing="0" border="0">
                    <tr>
                        <td class="address-details">
                            <h6>Bill to:</h6>
                            <p><span class="no-link">{{var order.getBillingAddress().format('html')}}</span></p>
                        </td>
                        {{depend order.getIsNotVirtual()}}
                        <td class="address-details">
                            <h6>Ship to:</h6>
                            <p><span class="no-link">{{var order.getShippingAddress().format('html')}}</span></p>
                        </td>
                        {{/depend}}
                    </tr>
                    <tr>
                        {{depend order.getIsNotVirtual()}}
                        <td class="method-info">
                            <h6>Shipping method:</h6>
                            <p>{{var order.shipping_description}}</p>
                        </td>
                        {{/depend}}
                        <td class="method-info">
                            <h6>Payment method:</h6>
                            {{var payment_html}}
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td class="order-details">
                If you have any question or require assistance with this order, do not hesitate to contact us and you can enjoy your shopping with us in the near future as well.
            </td>
        </tr>
    </table>
 
    {{template config_path="design/email/footer"}}

(2) Now open your custom module config.xml. if you have not any custom module then create it. Paste below code.

    <template>
        <email>
            <cancel_order_template translate="label">
                <label>Cancel Order</label>
                <file>sales/order_cancel.html</file>
                <type>html</type>
            </cancel_order_template>
        </email>
    </template>

   After this you can see your template in transaction email menu in magento admin panel.
 
(3) Now paste below code where you want to send the mail to customer. For example if you want mail after order cancel, then make observer for that and call below code in it.

    <?php
    /* Cancel order email to customer */
    $template = 'cancel_order_template';
    $sender = array('name' => Mage::getStoreConfig('trans_email/ident_sales/name'),
        'email' => Mage::getStoreConfig('trans_email/ident_sales/email'));
     
    //recepient
    $email = $order->getCustomerEmail();  // Customer Email
    $emaiName = $order->getCustomerName(); // Customer Name
    $paymentBlock = Mage::helper('payment')->getInfoBlock($order->getPayment())->setIsSecureMode(true);
    $paymentBlock->getMethod()->setStore($order->getStore()->getId());

    // Your dynamic variable
    $vars = array(
        'customer_name' => $order->getCustomerName(),
        'order_id' => $orderId,
        'order' => $order,
        'payment_html' => $paymentBlock->toHtml()
     );
 
    $order = Mage::app()->getLayout()->createBlock('sales/email_order_items');
    $storeId = Mage::app()->getStore()->getId();
    $translate = Mage::getSingleton('core/translate');
    Mage::getModel('core/email_template')->sendTransactional($template, $sender, $email, $emailName, $vars, $storeId);
    $translate->setTranslateInline(true);
    /* Cancel order email to customer */
   ?>

That's it... Enjoy Chandresh Rana Coding..

Thursday 4 August 2016

How to give discount on shipping charge magento


How to give discount on shipping charge magento

Code taken from here: http://magento.stackexchange.com/questions/52886/how-can-i-give-discount-on-shipping-costs

Navigate to Admin -> Promotions -> Shopping Cart Price Rule, from there fill in the fields as needed. When you get to the "Action" tab:

    Apply: Percent of Product Price Discount
    Discount Amount: The % off you want (just the number), e.g. 50
    Apply to Shipping Amount: Yes (this targets the shipping)

Now you want to make sure you don't target any products with the discount, so continue on the "Action" tab in the "Apply the rule only to cart items matching the following conditions" section, create a rule that applies to none of your products (e.g. SKU is {some SKU that doesn't exist}).


Example:


Code taken from here: http://magento.stackexchange.com/questions/52886/how-can-i-give-discount-on-shipping-costs

Thursday 16 June 2016

How to compress external images in magento


How to compress external images in magento

I have shown here image compressor code for who uses the custom module like Banner Module. You can also put this code in magento core functionality as well.

Put below function in your module controller where the image save code available

public function compress($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source);

elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source);

elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source);

imagejpeg($image, $destination, $quality);

return $destination;
}

Now call the above function after the image save code like this :

$this->compress($path.$_FILES['filename']['name'], $path.$_FILES['filename']['name'], 85);   // you can change the compressor ratio 85% to 90%

Tuesday 24 May 2016

How to insert indian state drop-down in magento


How to insert indian state drop-down in magento

Kindly run the below query into your magento database:

INSERT INTO `directory_country_region` VALUES
(NULL , "IN", "Andaman and Nicobar","Andaman and Nicobar"),
(NULL , "IN", "Andhra Pradesh","Andhra Pradesh"),
(NULL , "IN", "Arunachal Pradesh","Arunachal Pradesh"),
(NULL , "IN", "Assam","Assam"),
(NULL , "IN", "Bihar","Bihar"),
(NULL , "IN", "Chandigarh","Chandigarh"),
(NULL , "IN", "Chhattisgarh","Chhattisgarh"),
(NULL , "IN", "Dadra and Nagar Haveli","Dadra and Nagar Haveli"),
(NULL , "IN", "Daman and Diu","Daman and Diu"),
(NULL , "IN", "Delhi","Delhi"),
(NULL , "IN", "Goa","Goa"),
(NULL , "IN", "Gujarat","Gujarat"),
(NULL , "IN", "Haryana","Haryana"),
(NULL , "IN", "Himachal Pradesh","Himachal Pradesh"),
(NULL , "IN", "Jammu and Kashmir","Jammu and Kashmir"),
(NULL , "IN", "Jharkhand","Jharkhand"),
(NULL , "IN", "Karnataka","Karnataka"),
(NULL , "IN", "Kerala","Kerala"),
(NULL , "IN", "Lakshadweep","Lakshadweep"),
(NULL , "IN", "Madhya Pradesh","Madhya Pradesh"),
(NULL , "IN", "Maharashtra","Maharashtra"),
(NULL , "IN", "Manipur","Manipur"),
(NULL , "IN", "Meghalaya","Meghalaya"),
(NULL , "IN", "Mizoram","Mizoram"),
(NULL , "IN", "Nagaland","Nagaland"),
(NULL , "IN", "Orissa","Orissa"),
(NULL , "IN", "Pondicherry","Pondicherry"),
(NULL , "IN", "Punjab","Punjab"),
(NULL , "IN", "Rajasthan","Rajasthan"),
(NULL , "IN", "Sikkim","Sikkim"),
(NULL , "IN", "Tamil Nadu","Tamil Nadu"),
(NULL , "IN", "Tripura","Tripura"),
(NULL , "IN", "Uttar Pradesh","Uttar Pradesh"),
(NULL , "IN", "Uttaranchal","Uttaranchal"),
(NULL , "IN", "West Bengal","West Bengal");
 
INSERT INTO `directory_country_region_name` (`locale` ,`region_id` ,`name` ) SELECT 'en_US', tmp.region_id, tmp.default_name FROM `directory_country_region` AS tmp WHERE tmp.country_id='IN';

Thursday 19 May 2016

Solved: Coupon Codes Used when Payment pending Magento


Solved: Coupon Codes Used when Payment pending Magento

When site owner assign a single coupon code to customer and suppose customer use coupon without complete the order and he thought he will place the order next time then customer can not use this coupon in next order. In this case we have only two option to use coupon either you can increase the use of coupon or cancel the order. If customer cancel the order then you have to release the coupon on cancelling.

Here is the code to automatically decrease coupon usage upon a cancel the order.

Put below code in your module/any module config.xml file after <models> block

    <sales_order_payment_cancel>
        <observers>
          <order_cancel_couponfix_observer>
            <type>singleton</type>
            <class>Setblue_Banner_Model_Observer</class>
            <method>cancel</method>
          </order_cancel_couponfix_observer>
        </observers>
    </sales_order_payment_cancel>  

Next we need to create observer file to read this code. Create Observer.php in /yourmodule/Model/Observer.php and put the below code :

public function cancel($observer)
    {
$event = $observer->getEvent();
      $order = $event->getPayment()->getOrder();
        if ($order->canCancel()) {
if ($code = $order->getCouponCode()) {
$coupon = Mage::getModel('salesrule/coupon')->load($code, 'code');
if ($coupon->getTimesUsed() > 0) {
$customerId = $order->getCustomerId();
$resource = Mage::getSingleton('core/resource');
$writeConnection = $resource->getConnection('core_write');
$tableName = $resource->getTableName('salesrule_coupon_usage');

$query = "UPDATE {$tableName} SET times_used = times_used-1 "
.  "WHERE coupon_id = {$coupon->getId()} AND customer_id = {$customerId} AND times_used > 0";

$writeConnection->query($query);

$tableName = $resource->getTableName('salesrule_customer');
$query = "UPDATE {$tableName} SET times_used = times_used-1 "
.  "WHERE rule_id = {$coupon->getRuleId()} AND customer_id = {$customerId} AND times_used > 0";

$writeConnection->query($query);

}
                 
}
}
    }

Wednesday 27 April 2016

Set simple product price instead of attribute price in configurable product magento


Use simple product price instead of Super attribute price in configurable product magento

Kindly follow the below steps to change the super attribute price

First Use observers "catalog_product_get_final_price". Make observers like this :

Open your module config.xml and use below code :

<events>
    <catalog_product_get_final_price>
        <observers>
            <Setblue_Banner_Model_Observer>
                <type>singleton</type>
                <class>Setblue_Banner_Model_Observer</class>
                <method>getFinalPrice</method>
            </Setblue_Banner_Model_Observer>
        </observers>
    </catalog_product_get_final_price>
</events>

Now make the Observer.php file in model and past below code

<?php
class Setblue_Banner_Model_Observer
{

public function getFinalPrice(Varien_Event_Observer $observer) {

$event   = $observer->getEvent();
        $product = $event->getProduct();
        $qty     = $event->getQty();

$selectedAttributes = array();
if ($product->getCustomOption('attributes')) {
Mage::log('yes-----', null, 'confPricing.log');
$selectedAttributes = unserialize($product->getCustomOption('attributes')->getValue());
}

if (sizeof($selectedAttributes)) return $this->getSimpleProductPrice($qty, $product);

    }

public function getSimpleProductPrice($qty=null, $product)
    {

$cfgId = $product->getId();
        $product->getTypeInstance(true)
            ->setStoreFilter($product->getStore(), $product);
        $attributes = $product->getTypeInstance(true)
            ->getConfigurableAttributes($product);
        $selectedAttributes = array();
        if ($product->getCustomOption('attributes')) {
            $selectedAttributes = unserialize($product->getCustomOption('attributes')->getValue());
        }
        $db = Mage::getSingleton('core/resource')->getConnection('core_read');
        $dbMeta = Mage::getSingleton('core/resource');
        $sql = <<<SQL
SELECT main_table.entity_id FROM {$dbMeta->getTableName('catalog/product')} `main_table` INNER JOIN
{$dbMeta->getTableName('catalog/product_super_link')} `sl` ON sl.parent_id = {$cfgId}
SQL;
        foreach($selectedAttributes as $attributeId => $optionId) {
            $alias = "a{$attributeId}";
            $sql .= ' INNER JOIN ' . $dbMeta->getTableName('catalog/product') . "_int" . " $alias ON $alias.entity_id = main_table.entity_id AND $alias.attribute_id = $attributeId AND $alias.value = $optionId AND $alias.entity_id = sl.product_id";
        }
        $id = $db->fetchOne($sql);
        //Mage::log(Mage::getModel("catalog/product")->load($id)->getFinalPrice($qty), null, 'confPricing.log');
        //return
        $fp = Mage::getModel("catalog/product")->load($id)->getFinalPrice($qty);
        return $product->setFinalPrice($fp);
}

}

?>

Now open app/design/frontend/default/yourtheme/template/catalog/product/view/type/options/configurable.phtml and paste below code anywhere in file

<ul class="productIds" style="display:none;">
    <?php
        $configurableProduct = Mage::getModel('catalog/product')->load($_product->getId());
        $childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null,$configurableProduct);
        foreach($childProducts as $child) {
            $_productObj = Mage::getModel('catalog/product')->load($child->getId());
            ?>
            <li id='simple_<?php echo $child->getId(); ?>'><?php echo Mage::helper('core')->currency($_productObj->getFinalPrice()); ?></li>
        <?php  
        }
    ?>
</ul>  

Now open js/varien/configurable.js and change reloadPrice function as below or you can replace this whole function aswell

reloadPrice: function(){
    if (this.config.disablePriceReload) {
        return;
    }
    var price    = 0;
    var oldPrice = 0;
    for(var i=this.settings.length-1;i>=0;i--){
        var selected = this.settings[i].options[this.settings[i].selectedIndex];
        if(selected.config){
            price    += parseFloat(selected.config.price);
            oldPrice += parseFloat(selected.config.oldPrice);
        }
    }

    /* Edit Code By Chandresh Rana*/
 
     //optionsPrice.changePrice('config', {'price': price, 'oldPrice': oldPrice});
     optionsPrice.reload();
 
     var existingProducts = new Object();
     for(var i=this.settings.length-1;i>=0;i--)
     {
         var selected = this.settings[i].options[this.settings[i].selectedIndex];
         if(selected.config)
         {
            for(var iproducts=0;iproducts<selected.config.products.length;iproducts++)
            {
                var usedAsKey = selected.config.products[iproducts]+"";
                if(existingProducts[usedAsKey]==undefined)
                {
                    existingProducts[usedAsKey]=1;
                }
                else
                {
                    existingProducts[usedAsKey]=existingProducts[usedAsKey]+1;
                }
             }
         }
     }

     for (var keyValue in existingProducts)
     {
        for ( var keyValueInner in existingProducts)
         {
            if(Number(existingProducts[keyValueInner])<Number(existingProducts[keyValue]))
            {
                delete existingProducts[keyValueInner];
            }
         }
     }

     var sizeOfExistingProducts=0;
     var currentSimpleProductId = "";
     for ( var keyValue in existingProducts)
     {
        currentSimpleProductId = keyValue;
        sizeOfExistingProducts=sizeOfExistingProducts+1
     }

     if(sizeOfExistingProducts==1)
     {
        if($('product-price-'+this.config.productId)){
            $('product-price-'+this.config.productId).innerHTML = jQuery("#simple_"+currentSimpleProductId).html();
        }

     }
    // End Code By Chandresh Rana
 
    return price;

    if($('product-price-'+this.config.productId)){
        $('product-price-'+this.config.productId).innerHTML = price;
    }
    this.reloadOldPrice();
},

That's it. Enjoy Chandresh rana Coding....