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