Monday, December 3, 2012

Magento : add custom validation class

Consider form id is 'form_id' and custom class 'class_name'

var dataForm = new VarienForm('form_id', true);
 Validation.add('class_name','Alter message',function(the_field_value){
        if(the_field_value == '')
        {
            return false;
        }
        return true;
    });

Tuesday, November 27, 2012

Add Pin It Button to your site


Add Want Button to your site

Use script
<script>
(function() {
        var _w = document.createElement("script"); _w.type = "text/javascript"; _w.async = true;
        _w.src = "http://button.wanttt.com/button/script/";
        var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(_w, s);
})();
</script>
<a href="http://wanttt.com/want/initial_popup/"
data-merchant_name="ESCAPED_MERCHANT_NAME"
data-title="ESCAPED_PRODUCT_NAME"
data-price="PRODUCT_PRICE"
data-image_url="HIGH_RESOLUTION_PRODUCT_IMAGE_URL"
data-count="true"
data-style="wb1" data-page_source="PRODUCT" class="wantButton"></a>
 
 
or go to http://wantbutton.com/code.html

Tuesday, November 6, 2012

show plain text in a password field and then make it a regular password field on focus

Use html as
<input type="text" value="password" id="password">

And use script 
jQuery( document ).ready( function(){

    jQuery( document ).delegate( "#password", "focusin focusout",
        function(e){
        var elm = jQuery( "#password" )[0];
            if( e.type == "focusin" && elm.type == "text" ) {
            jQuery( elm ).replaceWith( jQuery( "<input>", {id: "password", type:"password", value:"" } ) );
            jQuery( "#password")[0].focus();
            }
            else if( e.type =="focusout" && elm.type == "password" && !elm.value ) {
                jQuery( elm ).replaceWith( jQuery( "<input>", {id: "password", type:"text", value:"password" } ) );
            }
        
        }
    );
});

Thursday, October 25, 2012

Creating virtual host in ubuntu

Suppose, the configuration file name is domain.com and local IP address is 127.0.0.1. Type following command in terminal
gksudo gedit /etc/apache2/sites-available/domain.com

Add following lines in configuration file
<VirtualHost 127.0.0.1:80>
    DocumentRoot /var/www/test
    ServerName domain.com
    ServerAlias test.domain.com
    ServerAdmin admin@domain.com
</VirtualHost>

Save and close it. Then create a symbolic link of this configuration file to /etc/apache2/sites-enabled directory in order to enable it
cd /etc/apache2/sites-enabled/
sudo ln -s ../sites-available/domain.com .

Then, add a virtual domain with a specific local IP to hosts file that is located in /etc/hosts. You can also add the port using a colon with the IP.
sudo nano /etc/hosts
add this line
127.0.0.1 test.domain.com
Save and close it. After all restart the apache service.

Magento : MySQL commands to clear all orders

SET FOREIGN_KEY_CHECKS=0;

TRUNCATE `sales_order`;
TRUNCATE `sales_order_datetime`;
TRUNCATE `sales_order_decimal`;
TRUNCATE `sales_order_entity`;
TRUNCATE `sales_order_entity_datetime`;
TRUNCATE `sales_order_entity_decimal`;
TRUNCATE `sales_order_entity_int`;
TRUNCATE `sales_order_entity_text`;
TRUNCATE `sales_order_entity_varchar`;
TRUNCATE `sales_order_int`;
TRUNCATE `sales_order_text`;
TRUNCATE `sales_order_varchar`;
TRUNCATE `sales_flat_quote`;
TRUNCATE `sales_flat_quote_address`;
TRUNCATE `sales_flat_quote_address_item`;
TRUNCATE `sales_flat_quote_item`;
TRUNCATE `sales_flat_quote_item_option`;
TRUNCATE `sales_flat_order_item`;
TRUNCATE `sendfriend_log`;
TRUNCATE `tag`;
TRUNCATE `tag_relation`;
TRUNCATE `tag_summary`;
TRUNCATE `wishlist`;
TRUNCATE `log_quote`;
TRUNCATE `report_event`;

ALTER TABLE `sales_order` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_datetime` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_decimal` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_datetime` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_decimal` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_int` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_text` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_entity_varchar` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_int` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_text` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_varchar` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_address` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_address_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_item_option` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_item` AUTO_INCREMENT=1;
ALTER TABLE `sendfriend_log` AUTO_INCREMENT=1;
ALTER TABLE `tag` AUTO_INCREMENT=1;
ALTER TABLE `tag_relation` AUTO_INCREMENT=1;
ALTER TABLE `tag_summary` AUTO_INCREMENT=1;
ALTER TABLE `wishlist` AUTO_INCREMENT=1;
ALTER TABLE `log_quote` AUTO_INCREMENT=1;
ALTER TABLE `report_event` AUTO_INCREMENT=1;

-- reset customers
TRUNCATE `customer_address_entity`;
TRUNCATE `customer_address_entity_datetime`;
TRUNCATE `customer_address_entity_decimal`;
TRUNCATE `customer_address_entity_int`;
TRUNCATE `customer_address_entity_text`;
TRUNCATE `customer_address_entity_varchar`;
TRUNCATE `customer_entity`;
TRUNCATE `customer_entity_datetime`;
TRUNCATE `customer_entity_decimal`;
TRUNCATE `customer_entity_int`;
TRUNCATE `customer_entity_text`;
TRUNCATE `customer_entity_varchar`;
TRUNCATE `log_customer`;
TRUNCATE `log_visitor`;
TRUNCATE `log_visitor_info`;

ALTER TABLE `customer_address_entity` AUTO_INCREMENT=1;
ALTER TABLE `customer_address_entity_datetime` AUTO_INCREMENT=1;
ALTER TABLE `customer_address_entity_decimal` AUTO_INCREMENT=1;
ALTER TABLE `customer_address_entity_int` AUTO_INCREMENT=1;
ALTER TABLE `customer_address_entity_text` AUTO_INCREMENT=1;
ALTER TABLE `customer_address_entity_varchar` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity_datetime` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity_decimal` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity_int` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity_text` AUTO_INCREMENT=1;
ALTER TABLE `customer_entity_varchar` AUTO_INCREMENT=1;
ALTER TABLE `log_customer` AUTO_INCREMENT=1;
ALTER TABLE `log_visitor` AUTO_INCREMENT=1;
ALTER TABLE `log_visitor_info` AUTO_INCREMENT=1;

-- Reset all ID counters
TRUNCATE `eav_entity_store`;
ALTER TABLE  `eav_entity_store` AUTO_INCREMENT=1;

SET FOREIGN_KEY_CHECKS=1;

Wednesday, October 3, 2012

Magento : add massDelete action in coupon code

First override Mage_Adminhtml_Block_Promo_Quote_Grid class and add following code
protected function _prepareMassaction()
    {
        $this->setMassactionIdField('rule_id');
        $this->getMassactionBlock()->setFormFieldName('rule');

        $this->getMassactionBlock()->addItem('delete', array(
             'label'    => Mage::helper('rule')->__('Delete'),
             'url'      => $this->getUrl('*/*/massDelete'),
             'confirm'  => Mage::helper('rule')->__('Are you sure?')
        ));
         return $this;
    }


then override Mage_Adminhtml_Promo_QuoteController class and add following code
public function massDeleteAction()
    { //exit;
        $rulesIds = $this->getRequest()->getParam('rule');
        if(!is_array($rulesIds)) {
             Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select rule(s).'));
        } else {
            try {
                $model = Mage::getModel('salesrule/rule');
                foreach ($rulesIds as $rulesId) {
                //echo $rulesId; exit;
                    $model->load($rulesId);
                    $model->delete();
                }
                Mage::getSingleton('adminhtml/session')->addSuccess(
                    Mage::helper('adminhtml')->__(
                        'Total of %d record(s) were deleted.', count($rulesIds)
                    )
                );
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            }
        }

        $this->_redirect('*/*/index');
    }

Magento : lazyloading in catloag page

Download lazyload js from below link
http://www.appelsiini.net/projects/lazyload
And save in js/lazyload/jquery.lazyload.js

Then create lazyload.phtml in template/lazyload/lazyload.phtml with following code
<script type="text/javascript" charset="utf-8">
    jQuery("img").load(function(){if(jQuery(this).attr("src")!=="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); ?>blank.png"){jQuery(this).removeAttr("height")}});

    jQuery(function() {
      jQuery("img").lazyload({
          effect : "fadeIn",     
      });
    });
</script>


And add following code in catalog.xml
<reference name="head">
    <action method="addJs"><script>jquery.lazyload.min.js"></script></action>
</reference>
<reference name="after_body_start">
      <block type="core/template" template="lazyloader/lazyload.phtml" name="lazyloader_init" />
</reference>

Remember that jquery must be included in site.

Magento : Add/Remove js file

Use following code
Add js through layout file
<reference name="head" as="head">
<action method="addJs"><script>folder_name/file_name.js</script></action>
</reference>
and through php code
echo $this->getLayout()->getBlock('head')->addJs('folder_name/file_name.js');

Remove js through layout file
<reference name="head" as="head">
<action method="removeItem"><type>js</type><name>folder_name/file_name.js</name</action>
</reference>
and though php code
$this->getLayout->getBlock('head')->removeItem('js','folder_name/file_name.js');

Monday, October 1, 2012

Magento : Zaakpay Payment Gateway Integration

Download kit from following link
https://www.zaakpay.com/developers/guide

And follow instructions given in ReadMe file.

Friday, September 28, 2012

Magento : Secure EBS Payment Gateway Integration

Download the module from following URL
https://support.ebs.in/app/index.php?/default_import/Knowledgebase/Article/View/226/7/magento-15-ebs-integrationkit-ver-25

Copy the folder Secureebs to magento\app\code\core\Mage\
Copy the file Mage_Secureebs.xml to magento\app\etc\modules\
Copy the folder secureebs to magento\app\design\frontend\base\default\template\
Add the file Mode.php inside magento\app\code\core\Mage\Adminhtml\Model\System\Config\Source\
Enter your Account Id , Secret Key and select the Mode from the EBS Payment Method control panel & Enable it.

Also we can add extra filed in Redirect.php

Thursday, September 27, 2012

Magento : Add configuration setting for custom module

Consider module Bd_Demo and model Test, then
Create System.xml in your module demo/etc
<?xml version="1.0"?>
<config>
    <tabs>
        <demo module="demo" translate="label">
            <label>Tab name</label>
            <sort_order>100</sort_order>
        </demo>
    </tabs>
  <sections>
    <demosection module="demo" translate="label">
      <label>Settings</label>
      <tab>demo</tab>
      <frontend_type>text</frontend_type>
      <sort_order>1000</sort_order>
      <show_in_default>1</show_in_default>
      <show_in_website>1</show_in_website>
      <show_in_store>1</show_in_store>
      <groups>
        <demogroup translate="label">
          <label>External Datatbase</label>
          <frontend_type>text</frontend_type>
          <sort_order>100</sort_order>
          <show_in_default>1</show_in_default>
          <show_in_website>1</show_in_website>
          <show_in_store>1</show_in_store>
          <fields>
            <!-- New fields go here -->
         <demofield translate="label comment">
              <label>Test Name</label>
              <comment>
                <![CDATA[This text appears just beneath the field with a small arrow.
                <span class="notice">It can contain HTML formatting too!</span>]]>
              </comment>
              <frontend_type>text</frontend_type>
              <sort_order>10</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>1</show_in_store>
            </demofield>    

          </fields>
        </demogroup>
      </groups>
    </demosection>
  </sections>
</config>

Then Define ACL in config.xml
<config>
    <adminhtml>
        <acl>
            <resources>
                <all>
                <title>Allow Everything</title>
                </all>
            <admin>
                <children>
                    <system>
                            <children>
                                <config>
                                    <children>
                                        <demosection>
                                            <title>Demo name</title>
                                                <children>
                                                    <demogroup>
                                                        <title>Settings</title>
                                                        <sort_order>1</sort_order>
                                                    </demogroup>
                                                   
                                                </children>
                                        </<demosection>
                                    </children>
                                </config>
                            </children>
                                </system>
                </children>
            </admin>
            </resources>
        </acl>
    </adminhtml>
</config> 

Also we access the value of this filed  as
Mage::getStoreConfig('demosection/demogroup/demofield ');

Also we can define the default value of this filed in config.xml
<config>
<default>
        <demosection>
            <demogroup>
                  <model>demo/test</model>                 
                  <demofield>Default Value</demofield>
            </demogroup>
        </demosection>
</default>
</config>

Magento : Add massdelete action in magento admin grid

Consider module Bd_Demo and model Test

Add following lines in _prepareMassaction() method of admin grid file
protected function _prepareMassaction()
{
    $this->setMassactionIdField('id');
    $this->getMassactionBlock()->setFormFieldName('test');
    $this->getMassactionBlock()->addItem('delete', array(
         'label'    => Mage::helper('demo')->__('Delete'),
         'url'      => $this->getUrl('*/*/massDelete'),
         'confirm'  => Mage::helper('demo')->__('Are you sure?')
    ));
           
    return $this;
}

And following method in admin controller
public function massDeleteAction()
{
        $webIds = $this->getRequest()->getParam('test');
        if(!is_array($webIds)) {
               Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select item(s)'));
        } else {
            try {
                foreach ($webIds as $webId) {
                    $web = Mage::getModel('demo/test')->load($webId);
                    $web->delete();
                }
                Mage::getSingleton('adminhtml/session')->addSuccess(
                    Mage::helper('adminhtml')->__(
                        'Total of %d record(s) were successfully deleted', count($webIds)
                    )
                );
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            }
        }
        $this->_redirect('*/*/index');
}

Magento : Add export CSV/XML functionality in magento admin grid

Consider module Bd_Demo and model Test, then
Add following lines in _prepareColumns() method of admin grid file
$this->addExportType('*/*/exportCsv', Mage::helper('demo')->__('CSV'));                              
$this->addExportType('*/*/exportXml', Mage::helper('demo')->__('XML'));

And add following methods in admin controller
public function exportCsvAction()
{
        $fileName   = 'test.csv';
        $content    = $this->getLayout()->createBlock('demo/adminhtml_test_grid')
            ->getCsv();

        $this->_sendUploadResponse($fileName, $content);
}

public function exportXmlAction()
{
        $fileName   = 'test.xml';
        $content    = $this->getLayout()->createBlock('demo/adminhtml_test_grid')
            ->getXml();

        $this->_sendUploadResponse($fileName, $content);
}

protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream')
{
        $response = $this->getResponse();
        $response->setHeader('HTTP/1.1 200 OK','');
        $response->setHeader('Pragma', 'public', true);
        $response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
        $response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
        $response->setHeader('Last-Modified', date('r'));
        $response->setHeader('Accept-Ranges', 'bytes');
        $response->setHeader('Content-Length', strlen($content));
        $response->setHeader('Content-type', $contentType);
        $response->setBody($content);
        $response->sendResponse();
        die;
}

Magento : Add custome button and remove button in magento admin grid

Consider module 'Bd_Demo' and Model 'Test'
Edit Grid Container File Test.php
public function __construct()
{
        $this->_controller = 'adminhtml_test';
        $this->_blockGroup = 'test';
        $this->_headerText = Mage::helper('demo')->__('Test Manager');
        $this->_addButtonLabel = Mage::helper('demo')->__('Add Test');


        $this->_addButton('button1', array(
            'label'     => Mage::helper('demo')->__('Button Label1'),
        'onclick'   => "setLocation('".$this->getUrl('*/*/button1')."')",
           
        ));

    $this->_removeButton('add'); // remove Add test button

        parent::__construct();
}

Note : button1Action() method must be in admin controller

Magento : How to use ajax in admin grid

Searching/paging and other operations to all work in admin grid using ajax, is built in functionality, only follow following step
In constructor of Grid.php file, add following lines   
$this->setSaveParametersInSession(true);
$this->setUseAjax(true);

And in Grid.php add the function   
public function getGridUrl()
{
    return $this->getUrl('*/*/grid', array('_current'=>true));
}

And in your ControllerNameContrller.php add the action   
public function gridAction()
{
    $this->loadLayout();
    $this->getResponse()->setBody(
        $this->getLayout()->createBlock('modulename/adminhtml_modelname_grid')->toHtml()
    );
}

Friday, September 21, 2012

Magento : Create an external database connection


Add the following code  to your config.xml under global tag

Consider Bd_test module

<global>

        <resources>

            <test_write>

                <connection>

                    <use>test_database</use>

                </connection>

            </test_write>

            <test_read>

                <connection>

                    <use>test_database</use>

                </connection>

            </test_read>

            <test_setup>

                <connection>

                    <use>core_setup</use>

                </connection>

            </test_setup>

            <test_database>

                <connection>

                    <host><![CDATA[localhost]]></host>

                    <username><![CDATA[db_username]]></username>

                    <password><![CDATA[db_password]]></password>

                    <dbname><![CDATA[db_name]]></dbname>

                    <model>mysql4</model>

                    <type>pdo_mysql</type>

                    <active>1</active>

                </connection>

            </test_database>

        </resources>

    </global>


Get data

    $resource   = Mage::getSingleton('core/resource');

    $conn       = $resource->getConnection('test_read');

    $results    = $conn->query('SELECT * FROM TableName');

    print_r($results)

Magento : Paypal is not working in Magento for Multishipping

Override folowing file code/core/Mage/Paypal/Model/Standard.php and Replace following code
protected $_canUseForMultishipping = flase; with protected $_canUseForMultishipping = true;

Magento : How to change product folder name in media

Rename product folder( media/catalog/product) to any name (like custom_product)

You need to change from all media path ‘product’ to ‘products’ to below listed files.

file_exists(Mage::getBaseDir('media').DS.'catalog'.DS.'product'.DS.$size.DS.$image)
to
file_exists(Mage::getBaseDir('media').DS.'catalog'.DS.'custom_product '.DS.$size.DS.$image)

Replace following code 'catalog/product/' to 'catalog/custom_product/' in following files
 Product/Attribute/Frontend/Image.php
 Product/Attribute/Media/Image.php
Product/Image.php
 Product/Media/Config.php
 Entity/Product/Attribute/Frontend/Image.php

Magento : How to encode product path image


Override following file /app/Local/Mage/Catalog/Helper/Image.php
and add following code
public function base64_encode_image ($filename=string) {
if ($filename) {

$forFiletype = explode('.',$ filename);
$forFiletype = array_reverse($forFiletype);
$filetype = $forFiletype[0];
if(strtoupper($filetype) == 'JPG')
{
$filetype = 'jpeg';
}
$base64image = '';
$changeFilePath = explode(‘cache’,$filename);
$changeFilePath = Mage::getBaseDir(). DS. ‘media’. DS. ‘catalog’.DS.’products’.DS.’cache’.$changeFilePath[1];
$imgbinary = fread(fopen($changeFilePath, “r”), filesize($changeFilePath));
return ‘data:image/’ . $filetype . ‘;base64,’ . base64_encode($imgbinary);
}
}

Now use in /app/design/catalog/product/list.phtml as
$this->helper('catalog/image')->init($_product, 'small_image')->resize(193,250);
$base64image = $this->helper('catalog/image')->base64_encode_image($product_image,$filetype);
<img src="<?php echo $this->getSkinUrl('images/spacer.png'); ?>" width="193" height="250" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" style="background:url(<?php echo $base64image;?>) no-repeat;"/>

Magento : Integrity constraint violation Column in where clause is ambiguous

Generally, This types of error come, when we are using join query or custom module 
Add ‘filter_index’=>’main_table.column_name’ in $this->addColumn() function

As
$this->addColumn('column_name', array(
'header' => Mage::helper('module')->__('Column Value'),
'align' =>'left',
'index' => 'column_name',
'filter_index'=>'main_table.column_name', // This parameter helps to resolve above error
));

Magento : Add custom column from custom table in magento admin grid


Use columns() method in collection as
 $collection->getSelect()->columns(new Zend_Db_Expr("[expression or any myql sub query] as custom_column"));

For example:

Consider Bd_Test module and override _prepareCollection() method in admin grid

protected function _prepareCollection()
                {
                 $collection = Mage::getModel('test/test')->getCollection();
     
                  $collection->getSelect()->columns(new Zend_Db_Expr("if((SELECT count(*) FROM table_name as  table_alias  WHERE table_alias.column > main_alias. column ) , 'NO', 'YES') as custom_column"));
               // echo $collection->getSelect();
                                $this->setCollection($collection);
                                return parent::_prepareCollection();
                }

Wednesday, September 19, 2012

Magento: Add google translator in website


Add following script in any template file

<div id="google_translate_element"></div><script>
function googleTranslateElementInit() {
  new google.translate.TranslateElement({
    pageLanguage: 'en'
  }, 'google_translate_element');
}
</script><script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

Monday, September 17, 2012

Show More /Less link using jQuery

Sample text:
<div class="comment more">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Vestibulum laoreet, nunc eget laoreet sagittis,
    quam ligula sodales orci, congue imperdiet eros tortor ac lectus.
    Duis eget nisl orci. Aliquam mattis purus non mauris
    blandit id luctus felis convallis.
    Integer varius egestas vestibulum.
    Nullam a dolor arcu, ac tempor elit. Donec.
</div>
 
 
CSS: 

a {
    color: #0254EB
}
a:visited {
    color: #0254EB
}
a.morelink {
    text-decoration:none;
    outline: none;
}
.morecontent span {
    display: none;
}
.comment {
    width: 400px;
    background-color: #f0f0f0;
    margin: 10px;
}
 
Javascript:
$(document).ready(function() {
    var showChar = 100;
    var ellipsestext = "...";
    var moretext = "more";
    var lesstext = "less";
    $('.more').each(function() {
        var content = $(this).html();
 
        if(content.length > showChar) {
 
            var c = content.substr(0, showChar);
            var h = content.substr(showChar, content.length - showChar);
 
            var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';
 
            $(this).html(html);
        }
 
    });
 
    $(".morelink").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });
});
 

Wednesday, August 22, 2012

Magento : Allow tags (iframe, embed) in CMS editor

Add following code in file: js/mage/adminhtml/wysiwyg/tiny_mce/setup.js
after line
theme_advanced_resizing : true,


extended_valid_elements : 'iframe[src|style|width|height|scrolling|marginwidth|marginheight|frameborder],style,script',

Friday, August 17, 2012

Magento : Enablle specific payment method for specific IP address

Consider module as Bd_Testpament
Add a filed for Ip in system.xml with follwoing code
<config>
   <sections>
        <payment>
            <groups>
                <testpayment translate="label comment" module="testpayment">
                    <label>Test</label>
                    <comment>Test</comment>
                    <frontend_type>text</frontend_type>
                    <sort_order>256</sort_order>
                    <show_in_default>1</show_in_default>
                    <show_in_website>1</show_in_website>
                    <show_in_store>0</show_in_store>
                    <fields>
            <allowed_ips translate="label">
            <label>Allowed Ips</label>
            <frontend_type>text</frontend_type>
            <sort_order>130</sort_order>
            <show_in_default>1</show_in_default>
            <show_in_website>1</show_in_website>
            <show_in_store>0</show_in_store>
            </allowed_ips>
                    </fields>
                </secureebsoffer_standard>
            </groups>
        </payment>
    </sections>
</config>

And edit __construct of model with following code

public function __construct()
    {
        parent::__construct();
       
        $allowed_ips=Mage::getStoreConfig('payment/testpayment/allowed_ips');
       
        if($allowed_ips !='')
        {
       
            if(!in_array($_SERVER['HTTP_X_FORWARDED_FOR'],explode(",",$allowed_ips)))
            {
                $this->_canUseCheckout=false;
               
            }
        }
        else
        {
                $this->_canUseCheckout=false;
        }

Wednesday, August 8, 2012

Magento : sharing the cart between stores

The first thing enable the Use SID on Frontend at
System→Configuration→Web→Session

Then replace following code in start() method of Mage_Core_Model_Session_Abstract_Varien
if (isset($_SESSION)) {
            return $this;
        }

with
if (isset($_SESSION) && !isset($_GET['SID'])) {
            return $this;
        }

Magento : MassDelete & Status action in admin grid

Consider Package: Bd, Module : Test & Model : Test

1.Override _prepareMassaction() method in Grid.php with following code

protected function _prepareMassaction()
    {
        $this->setMassactionIdField('test_id');
        $this->getMassactionBlock()->setFormFieldName('test');

        $this->getMassactionBlock()->addItem('delete', array(
             'label'    => Mage::helper('test')->__('Delete'),
             'url'      => $this->getUrl('*/*/massDelete'),
             'confirm'  => Mage::helper('test')->__('Are you sure?')
        ));

        $statuses = Mage::getSingleton('test/status')->getOptionArray();

        array_unshift($statuses, array('label'=>'', 'value'=>''));
        $this->getMassactionBlock()->addItem('status', array(
             'label'=> Mage::helper('test')->__('Change status'),
             'url'  => $this->getUrl('*/*/massStatus', array('_current'=>true)),
             'additional' => array(
                    'visibility' => array(
                         'name' => 'status',
                         'type' => 'select',
                         'class' => 'required-entry',
                         'label' => Mage::helper('test')->__('Status'),
                         'values' => $statuses
                     )
             )
        ));
        return $this;
    }


2.Create two action in admin controller with following code
public function massDeleteAction() {
        $testIds = $this->getRequest()->getParam('test');
        if(!is_array($testIds)) {
   Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select item(s)'));
        } else {
            try {
                foreach ($testIds as $testId) {
                    $test = Mage::getModel('test/test')->load($testId);
                    $test->delete();
                }
                Mage::getSingleton('adminhtml/session')->addSuccess(
                    Mage::helper('adminhtml')->__(
                        'Total of %d record(s) were successfully deleted', count($testIds)
                    )
                );
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            }
        }
        $this->_redirect('*/*/index');
    }

    public function massStatusAction()
    {
        $testIds = $this->getRequest()->getParam('test');
        if(!is_array($testIds)) {
            Mage::getSingleton('adminhtml/session')->addError($this->__('Please select item(s)'));
        } else {
            try {
                foreach ($testIds as $testId) {
                    $test = Mage::getSingleton('test/test')
                        ->load($testId)
                        ->setStatus($this->getRequest()->getParam('status'))
                        ->setIsMassupdate(true)
                        ->save();
                }
                $this->_getSession()->addSuccess(
                    $this->__('Total of %d record(s) were successfully updated', count($testIds))
                );
            } catch (Exception $e) {
                $this->_getSession()->addError($e->getMessage());
            }
        }
        $this->_redirect('*/*/index');
    }

Object Expected error in Internet Explorer

This error usually happens in the following scenario. An HTML file contains an inline JavaScript to load remote.js and call a function in remote.js

<script type="text/javascript">
//<![CDATA[
    Event.observe(window, 'load', function() {
        product_zoom = new Product.Zoom('image', 'track', 'handle', 'zoom_in', 'zoom_out', 'track_hint');
    });
//]]>
</script>

And in the file remote.js:
remoteFunction code.....


You would expect the output in this order:

    Before loading remote.js
    After loading remote.js
    In remote function

IE gives an error message "Object Expected" because it calls the function remoteFunction() prematurely. It calls before loading the file remote.js, which contain the declaration of remoteFunction(). This is another unexpected behavior from IE. Fortunately, it can be corrected by adding the attribute defer="defer" to second script invocation. This will specifically prevent IE from executing in order to give a correct output. Other browsers are not affected by the change.

Tuesday, August 7, 2012

Magento: Tag Url Rewrite and Generate

Rewrite the tag/tag model and override the getTaggedProductsUrl() with the following code
public function getTaggedProductsUrl()
{
    $fullTargetPath = Mage::getUrl('tag/product/list', array(
        'tagId' => $this->getTagId(),
        '_nosid' => true
    ));
    $targetPath = substr($fullTargetPath, strlen(Mage::getBaseUrl()));
    $rewriteUrl = Mage::getModel('core/url_rewrite')->loadByIdPath($targetPath);
    if ($rewriteUrl->getId()) {
        return $rewriteUrl->getRequestPath();
    }
    return $fullTargetPath;
}

Friday, July 20, 2012

Magento : Define Global, Website, Store, Store View

    Global: This refers to the entire installation.
    Website: Websites are ‘parents’ of stores.  A website consists of one or more stores. Websites can be set up to share customer data, or not to share any data
    Store (or store view group): Stores are ‘children’ of websites.  Products and Categories are managed on the store level.  A root category is configured for each store view group, allowing multiple stores under the same website to have totally different catalog structures.
    Store View: A store needs one or more store views to be browse-able in the front-end.  The catalog structure per store view will always be the same, it simply allows for multiple presentations of the data in the front.  90% of implementations will likely use store views to allow customers to switch between 2 or more languages.

Magento : get file paths and URLs

Get URL paths of your magento folder structure – Absolute URL Path

Mage::getBaseUrl() => Gets base url path e.g. http://my.website.com/

Mage::getBaseUrl(‘media’) => Gets MEDIA folder path e.g. http://my.website.com/media/

Mage::getBaseUrl(‘js’) => Gets JS folder path e.g. http://my.website.com/js/

Mage::getBaseUrl(‘skin’) => Gets SKIN folder path e.g. http://my.website.com/skin/

Get DIRECTORY paths (physical location of your folders on the server) – Relative URL Path

Mage::getBaseDir() => Gives you your Magento installation folder / root folder e.g. /home/kalpesh/workspace/magento

Mage::getBaseDir(‘app’) => Gives you your Magento’s APP directory file location e.g. /home/kalpesh/workspace/magento/app

Mage::getBaseDir(‘design’) => Gives you your Magento’s DESIGN directory file location e.g. /home/kalpesh/workspace/magento/design

Mage::getBaseDir(‘media’) => Gives MEDIA directory file path

Mage::getBaseDir(‘code’) => Gives CODE directory file path

Mage::getBaseDir(‘lib’) => Gives LIB directory file path

Get Current URL – whole URL path

Mage::helper(‘core/url’)->getCurrentUrl()

Also we can use as

base Mage::getBaseDir()
Mage::getBaseDir(‘base’) /var/www/magento/
app Mage::getBaseDir(‘app’) /var/www/magento/app/
code Mage::getBaseDir(‘code’) /var/www/magento/app/code
design Mage::getBaseDir(‘design’) /var/www/magento/app/design/
etc Mage::getBaseDir(‘etc’) /var/www/magento/app/etc
lib Mage::getBaseDir(‘lib’) /var/www/magento/lib
locale Mage::getBaseDir(‘locale’) /var/www/magento/app/locale
media Mage::getBaseDir(‘media’) /var/www/magento/media/
skin Mage::getBaseDir(‘skin’) /var/www/magento/skin/
var Mage::getBaseDir(‘var’) /var/www/magento/var/
tmp Mage::getBaseDir(‘tmp’) /var/www/magento/var/tmp
cache Mage::getBaseDir(‘cache’) /var/www/magento/var/cache
log Mage::getBaseDir(‘log’) /var/www/magento/var/log
session Mage::getBaseDir(‘session’) /var/www/magento/var/session
upload Mage::getBaseDir(‘upload’) /var/www/magento/media/upload
export Mage::getBaseDir(‘export’) /var/www/magento/var/export

Thursday, July 19, 2012

Magento : add thumnail in admin grid

Remember that grid is working fine.Here module is consider as Bd_Collegeprogram

First add the code in the _prepareColumns() function
$this->addColumn("image", array(
                "header" => Mage::helper("collegeprogram")->__("Image"),
                "index" => "image",
                'type' => 'image',
                'width' => '50px',
                'renderer'  => 'collegeprogram/adminhtml_collegeprogram_renderer_image'
                ));
Now create a block as adminhtml_collegeprogram_renderer_image
class Bd_Collegeprogram_Block_Adminhtml_collegeprogram_Renderer_Image extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract{

    public function render(Varien_Object $row)
    {
        $html = '<img ';
        $html .= 'id="' . $this->getColumn()->getId() . '" ';
        $html .= 'src="' . $row->getData($this->getColumn()->getIndex()) . '"';
        $html .= 'class="grid-image ' . $this->getColumn()->getInlineCss() . '"/>';
        return $html;
    }
}

Monday, June 18, 2012

Magento Show Top Navigation with Thumnail

1.Add new function getThumbnailUrl in Mage\Catalog\Model\Category.php

public function getThumbnailUrl()
 {
  $url = false;
  if ($image = $this->getThumbnail()) {
   $url = Mage::getBaseUrl('media').'catalog/category/'.$image;
  }
  return $url;
 }

2.Add new function getThumbnailUrl in Mage\Catalog\Block\Navigation.php

public function getThumbnailUrl($category)
{
 return Mage::getModel('catalog/category')->load($category->getId())->getThumbnailUrl();
}

3. Use getThumbnailUrl to show thumnail in top navigation

Use as:
Open app\code\core\Mage\Catalog\Block\Navigation.php, then serach for html generate _renderCategoryMenuItemHtml method, here you can change html as

Replace $html[] = '<span>' . $this->escapeHtml($category->getName()) . '</span>';
with
$html[] = '<img src="'.$this->getThumbnailUrl($category).'" alt="'. $this->escapeHtml($category->getName()).'" />';

Magento Layered navigation at home page


Follow as
1.Update XML layout via CMS > Manage Pages > Homepage > Layout Update XML box:
<reference name="left">
    <block type="catalog/layer_view" name="catalog.leftnav" after="currency" template="catalog/layer/view.phtml"/>
</reference>

2.Modify a core method getCurrentCategory() in core/Mage/Catalog/Model/Layer.php
public function getCurrentCategory()
    {
        $category = $this->getData('current_category');

        if (is_null($category)) {
            if ($category = Mage::registry('current_category')) {
                $this->setData('current_category', $category);
            }
            else {
                $category = Mage::getModel('catalog/category')->load($this->getCurrentStore()->getRootCategoryId());
                $this->setData('current_category', $category);
            }
        }

        if($category != Mage::registry('current_category')) {          
            $home_category = Mage::getModel('catalog/category')->load(3);
            $this->setData('current_category', $home_category);
            $category = $this->getData('current_category');
            //return $category;
        }
     
        return $category;
    }

Saturday, June 16, 2012

Magento : Replacing the Logo Image in Transactional Emails

To replace the logo image, upload the new logo image into the images directory and rename the file as logo_email.gif, overwriting the existing image. Also, and very importantly, to ensure that the new image will show up in the transactional emails, the permissions need to be changed so that it includes read and write permissions. 

Magento: Terms and Conditions

Setting up Terms and Conditions for your Magento store is a two-step process:

Step 1: Enable Terms and Conditions in your store's checkout process

    From the Admin panel, select System > Configuration.
    From the Configuration panel on the left, under Sales, select the Checkout tab.
    If necessary, click to expand the Checkout Options section. Terms and Conditions Checkout Options
    Make sure that Enable Onepage Checkout is set to Yes.

   To display a checkbox that describes your store's terms and conditions during checkout, set Enable Terms and Conditions to Yes.
Click the Save Config button.



Step 2: Create a Terms and Conditions checkbox

From the Admin panel, select Sales > Terms and Conditions.
To add new terms and conditions, click the Add New button.
Complete the following information:
    Enter a Condition Name for this condition.
    To make your Terms and Conditions checkbox appear during customer checkout, set Status to Enabled.
    Select whether you want your Terms and Conditions Document to appear as Text or HTML. If you want to use bold or underline or other formatting in the document, you can use HTML tags to achieve that formatting. To use HTML tags, set Show Content as to HTML.
Identify the Store View where the Terms and Conditions will appear.
Enter the Checkbox Text that you want to appear with the checkbox. For example, you could use "I understand and accept these terms and conditions" or "Accept" or whatever specific terms and conditions you want your customers to acknowledge.
In the Content field, enter text to describe the terms and conditions of the sale.
Optional: You can set Content Height (css) in pixels to determine the height of the text box that contains the terms and conditions content. For example, if you want the text box to be one inch high, enter the equivalent value in pixels.
Click the Save Condition button.



Thursday, June 7, 2012

Could not determine temp directory, please specify a cache_dir manually in magento


You have to open magento/lib/Zend/Cache/Backend/File.php
Change:

protected $_options = array(
        'cache_dir' => 'null',
to
protected $_options = array(
        'cache_dir' => 'tmp/',

Upload the changed File.php and create a folder, called “tmp”
The folder must be writable, so give it ‘777’

Fatal error: Allowed memory size of 33554432 bytes exhausted in magento


This is because of the PHP Memory Limit.
Here is how to fix.
Goto your website root from FTP.
You will see a file called php.ini.sample
Rename it to php.ini
Edit that file and Copy/Paste this code at last,
   extension=pdo.so
   extension=pdo_mysql.so
  extension=pdo_sqlite.so

Wednesday, May 30, 2012

URL redirection after tracking the visitor's IP address it will automatically land the visitor to the corresponding website in Magento

First crate a file in root folder named: ip.php, and copy/paste following code or download from http://ipinfodb.com/index.php


<?php
final class ip2location_lite{
protected $errors = array();
protected $service = 'api.ipinfodb.com';
protected $version = 'v3';
protected $apiKey = 'efd67dca864cbe8b45fb21b7d19916bf471afd1bfcfe0b3e975d1f238d6c7ed3';

public function __construct(){}

public function __destruct(){}

public function setKey($key){
if(!empty($key)) $this->apiKey = $key;
}

public function getError(){
return implode("\n", $this->errors);
}

public function getCountry($host){
return $this->getResult($host, 'ip-country');
}

public function getCity($host){
return $this->getResult($host, 'ip-city');
}

private function getResult($host, $name){
$ip = @gethostbyname($host);

if(preg_match('/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', $ip)){
$xml = @file_get_contents('http://' . $this->service . '/' . $this->version . '/' . $name . '/?key=' . $this->apiKey . '&ip=' . $ip . '&format=xml');

try{
$response = @new SimpleXMLElement($xml);

foreach($response as $field=>$value){
$result[(string)$field] = (string)$value;
}

return $result;
}
catch(Exception $e){
$this->errors[] = $e->getMessage();
return;
}
}

$this->errors[] = '"' . $host . '" is not a valid IP address or hostname.';
return;
}
}
?>


Then open index file of magento nad copy/paste following code at the top


$protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
$url = $protocol.'://'.$_SERVER['SERVER_NAME']; //  More efficient manner
//echo $url;

include('ip.php');
$ipLite = new ip2location_lite;
//$ipAddress = '62.68.127.255';
$ipAddress = $_SERVER['REMOTE_ADDR'];
$locations = $ipLite->getCountry($ipAddress);
$countryCode = strtoupper(trim($locations['countryCode']));
//$countryCode='CA';
//$country_cd = substr($_SERVER['SERVER_NAME'],0,-2);



switch($countryCode){
case 'CA': /* Cananda */
if($url != 'http://www.yourdomain.ca'){
header('location: http://www. yourdomain .ca'.$_SERVER['REQUEST_URI']);
}
break;

case 'UK': /* United States */
if($url != 'http://www. yourdomain .co.uk'){
header('location: http://www. yourdomain .co.uk'.$_SERVER['REQUEST_URI']);
}
break;

case 'DE': /* Germany/Dutch */
if($url != 'http://www. yourdomain .de'){
header('location: http://www. yourdomain .de'.$_SERVER['REQUEST_URI']);
}
break;

case 'SE': /* Sweden */
if($url != 'http://www. yourdomain .se'){
header('location: http://www. yourdomain .se'.$_SERVER['REQUEST_URI']);
}
break;

/* For European Countries Start */

case 'RU': //Russia
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'FR': //France
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'UA': //Ukraine
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'ES': //spain
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'SE': //sweden
if($url != 'http://www.handbagbutler.eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'NO': //Norway
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'FI': //Finland
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'PL': //Poland
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'IT': //Italy
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'RO': //Romania
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'BY': //Belarus
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'KZ': //Kazakhstan
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'GR': //Greece
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'BG': //Bulgaria
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'IS': //Iceland
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'HU': //Hungary
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'PT': //Portugal
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'RS': //Serbia
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu/'.$_SERVER['REQUEST_URI']);
}
break;

case 'AT': //Austria
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'CZ': //Czech Republic
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'IE': //Republic of Ireland
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'GE': //Georgia
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'LT': //Lithuania
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'LV': //Latvia
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'RO': //Croatia
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

case 'BA': //Bosnia and Herzegovina
if($url != 'http://www. yourdomain .eu'){
header('location: http://www. yourdomain .eu'.$_SERVER['REQUEST_URI']);
}
break;

/* For European Countries End */

default: /* Default */
if($url != 'http://www. yourdomain .com'){
header('location: http://www. yourdomain .com'.$_SERVER['REQUEST_URI']);
}
break;
}