Wednesday, 5 September 2012

How to set up a multiple store in Magento



(A)        Multi-Web-Site, Multi-Domain Setup :-

Follow Multi Web-Site and Multi Store Instructions.

1: Categories

First, will need to create our Categories.  Since all three websites will be sharing the same catalog, we will be using the default root Category in Catalog -> Categories -> Manage Categories and will be creating our categories under that root category (i.e. Clothing, Electronics, etc.).
image
These categories (Clothing, Electronics) should be set as both “Is Active” from the General Information tab and “Is Anchor” from the Display Settings tab for them to appear on the frontend of your Magento shop.  (***NOTE: If the websites will not be sharing the same catalog, a Root Category must be created for each website.  Thus, if there are 3 websites, there will be 3 Root Categories with subcategories under them.)

2: Store Configuration in the Magento Admin

1. Now that we have created our Categories, it’s time to create our websites by going to System -> Manage Stores and clicking the “Create Website” button.

  • Name – domain name of our new website
  • Code – a parameter that will be used in configuring the Apache web server to point to that particular domain name

image
2. Once the website has been created, we’ll create the store corresponding to this website by clicking on the “Create Store” button in System -> Manage Stores.
  • Website – website to which this store will be associated
  • Name – the same as the website name
  • Root Category – the root category that will be used for this store. (Refer to Step 1 for Details)

image
3. Then, we create the store view which is the interface that the customer will be able to access on the frontend.  Click the “Create Store View” button in System -> Manage Stores.

  • Store – store to which this view will be associated
  • Name – name of this store view (i.e. English Version, German Version, etc.)
  • Code – code for this store view
  • Status – if enabled, this store view will be accessible from our frontend, otherwise, it will not be accessible

image
4. After the Store has been created, we need to configure the Unsecure Base URL and Secure Base URL under System -> Configuration -> General -> Web.  Before we set their respective base URLs, we first need to ensure that the configuration scope is set to the domain1.com website to define which site we are working on.
image
Then, we modify the base URLs for both Unsecure:
image
and Secure:
image
with the corresponding domain name by unchecking the ”Use default [STORE VIEW]” checkbox and then save the configuration.
5. Now we just repeat Steps 2-4 for the other two websites, domain2.com and domain3.com by replacing the fields with their respective information.

3: Store Configuration in the Server

(B)  Two Way of Store Configuration :- Choose as Like You .

First Way :-

1: Store Configuration in the Server Side.

1. Now we re-configure the Apache configuration file, httpd.conf, for all domains to set the DocumentRoot to our Magento directory.  In this case, the directory is /var/www/http

<VirtualHost *:80>
    ServerAdmin webmaster@domain1.com
    DocumentRoot /var/www/http
    ServerName domain0.com
</VirtualHost>
 
<VirtualHost *:80>
    ServerAdmin webmaster@domain2.com
    DocumentRoot /var/www/http
    ServerName domain1.com
</VirtualHost>
 
<VirtualHost *:80>
    ServerAdmin webmaster@domain3.com
    DocumentRoot /var/www/http
    ServerName domai2.com
</VirtualHost>

2. Edit the .htaccess file at /var/www/http/.htaccess and add the following lines below:

SetEnvIf Host www\.domain1\.com MAGE_RUN_CODE=domain1_com
SetEnvIf Host www\.domain1\.com MAGE_RUN_TYPE=website
SetEnvIf Host ^domain1\.com MAGE_RUN_CODE=domain1_com
SetEnvIf Host ^domain1\.com MAGE_RUN_TYPE=website
 
SetEnvIf Host www\.domain2\.com MAGE_RUN_CODE=domain2_com
SetEnvIf Host www\.domain2\.com MAGE_RUN_TYPE=website
SetEnvIf Host ^domain2\.com MAGE_RUN_CODE=domain2_com
SetEnvIf Host ^domain2\.com MAGE_RUN_TYPE=website
 
SetEnvIf Host www\.domain3\.com MAGE_RUN_CODE=domain3_com
SetEnvIf Host www\.domain3\.com MAGE_RUN_TYPE=website
SetEnvIf Host ^domain3\.com MAGE_RUN_CODE=domain3_com
SetEnvIf Host ^domain3\.com MAGE_RUN_TYPE=website

3. Restart Apache Server
If you are on a Red Hat based distribution, you’ll be able to type service apache restart.  For other distributions, you’ll want to type apachectl restart.  (***NOTE: The second option here is different than “apachectl graceful” which will run a graceful restart and reload configuration files, without terminating current connections.  We don’t have any visitors to our site yet, so it’s okay to do a “apachectl restart”.)

4: We’re Ready to Go!

After we’ve complete all of these steps we should now see all 3 domains in our backend:
image
All that’s left now is to add products to the catalog and give each site a custom theme if we wish to do so.  Many people are taking advantage of Magento’s powerful multi-store functionality, whether it’s to set up stores with multiple languages, different catalogs and even the same catalogs (as in our example) with different front ends as a marketing vehicle.  No matter which you decide to use Magento’s powerful features for, we hope this post will provide a good starting point to help you get there!

Second Way :-


1: Web-Site &Store Configuration in the Index.php .

Complete Create  Root category And Website, store, store view then process  again. Open index.php in magento  Root Folder some changes Doc file according.
First,  Find this line code and replace.
Find  = $mageFilename = MAGENTO_ROOT . '/app/Mage.php';
Replace = $mageFilename = MAGENTO_ROOT . '../app/Mage.php';





Second ,  Find this line code and replace.
Find  =  Mage::run($mageRunCode, $mageRunType);
Replace  =

$i=$_SERVER['REQUEST_URI'];
switch ($i):
    case 'www.domain1.com':
         Mage::run("domain1","website");
        break;
    case 'www.domain2.com':
         Mage::run("domain2","website");
        break;
    case 'www.domain3.com':
         Mage::run("domain3","website");
        break;
    default:
       Mage::run("default","website");
endswitch;
 multi.JPG

After Completed two major change save index.php file in root folder. Delete all cache and Re-indexing admin panel. After restart apache server. Then check our Multi-domain website is ready for running.
Magento’s provide  powerful multi-store functionality . I hope this instruction  will provide a good starting point to help you get there!

End .

 Important Link Multi-Store & Multi Web-Site

How to set up a multiple website in Magento



(A)        Multi-Web-Site, Multi-Domain Setup :-

Follow Multi Web-Site and Multi Store Instructions.

1: Categories

First, will need to create our Categories.  Since all three websites will be sharing the same catalog, we will be using the default root Category in Catalog -> Categories -> Manage Categories and will be creating our categories under that root category (i.e. Clothing, Electronics, etc.).
image
These categories (Clothing, Electronics) should be set as both “Is Active” from the General Information tab and “Is Anchor” from the Display Settings tab for them to appear on the frontend of your Magento shop.  (***NOTE: If the websites will not be sharing the same catalog, a Root Category must be created for each website.  Thus, if there are 3 websites, there will be 3 Root Categories with subcategories under them.)

2: Store Configuration in the Magento Admin

1. Now that we have created our Categories, it’s time to create our websites by going to System -> Manage Stores and clicking the “Create Website” button.

  • Name – domain name of our new website
  • Code – a parameter that will be used in configuring the Apache web server to point to that particular domain name

image
2. Once the website has been created, we’ll create the store corresponding to this website by clicking on the “Create Store” button in System -> Manage Stores.
  • Website – website to which this store will be associated
  • Name – the same as the website name
  • Root Category – the root category that will be used for this store. (Refer to Step 1 for Details)

image
3. Then, we create the store view which is the interface that the customer will be able to access on the frontend.  Click the “Create Store View” button in System -> Manage Stores.

  • Store – store to which this view will be associated
  • Name – name of this store view (i.e. English Version, German Version, etc.)
  • Code – code for this store view
  • Status – if enabled, this store view will be accessible from our frontend, otherwise, it will not be accessible

image
4. After the Store has been created, we need to configure the Unsecure Base URL and Secure Base URL under System -> Configuration -> General -> Web.  Before we set their respective base URLs, we first need to ensure that the configuration scope is set to the domain1.com website to define which site we are working on.
image
Then, we modify the base URLs for both Unsecure:
image
and Secure:
image
with the corresponding domain name by unchecking the ”Use default [STORE VIEW]” checkbox and then save the configuration.
5. Now we just repeat Steps 2-4 for the other two websites, domain2.com and domain3.com by replacing the fields with their respective information.

3: Store Configuration in the Server

(B)  Two Way of Store Configuration :- Choose as Like You .

First Way :-

1: Store Configuration in the Server Side.

1. Now we re-configure the Apache configuration file, httpd.conf, for all domains to set the DocumentRoot to our Magento directory.  In this case, the directory is /var/www/http

<VirtualHost *:80>
    ServerAdmin webmaster@domain1.com
    DocumentRoot /var/www/http
    ServerName domain0.com
</VirtualHost>
 
<VirtualHost *:80>
    ServerAdmin webmaster@domain2.com
    DocumentRoot /var/www/http
    ServerName domain1.com
</VirtualHost>
 
<VirtualHost *:80>
    ServerAdmin webmaster@domain3.com
    DocumentRoot /var/www/http
    ServerName domai2.com
</VirtualHost>

2. Edit the .htaccess file at /var/www/http/.htaccess and add the following lines below:

SetEnvIf Host www\.domain1\.com MAGE_RUN_CODE=domain1_com
SetEnvIf Host www\.domain1\.com MAGE_RUN_TYPE=website
SetEnvIf Host ^domain1\.com MAGE_RUN_CODE=domain1_com
SetEnvIf Host ^domain1\.com MAGE_RUN_TYPE=website
 
SetEnvIf Host www\.domain2\.com MAGE_RUN_CODE=domain2_com
SetEnvIf Host www\.domain2\.com MAGE_RUN_TYPE=website
SetEnvIf Host ^domain2\.com MAGE_RUN_CODE=domain2_com
SetEnvIf Host ^domain2\.com MAGE_RUN_TYPE=website
 
SetEnvIf Host www\.domain3\.com MAGE_RUN_CODE=domain3_com
SetEnvIf Host www\.domain3\.com MAGE_RUN_TYPE=website
SetEnvIf Host ^domain3\.com MAGE_RUN_CODE=domain3_com
SetEnvIf Host ^domain3\.com MAGE_RUN_TYPE=website

3. Restart Apache Server
If you are on a Red Hat based distribution, you’ll be able to type service apache restart.  For other distributions, you’ll want to type apachectl restart.  (***NOTE: The second option here is different than “apachectl graceful” which will run a graceful restart and reload configuration files, without terminating current connections.  We don’t have any visitors to our site yet, so it’s okay to do a “apachectl restart”.)

4: We’re Ready to Go!

After we’ve complete all of these steps we should now see all 3 domains in our backend:
image
All that’s left now is to add products to the catalog and give each site a custom theme if we wish to do so.  Many people are taking advantage of Magento’s powerful multi-store functionality, whether it’s to set up stores with multiple languages, different catalogs and even the same catalogs (as in our example) with different front ends as a marketing vehicle.  No matter which you decide to use Magento’s powerful features for, we hope this post will provide a good starting point to help you get there!

Second Way :-


1: Web-Site &Store Configuration in the Index.php .

Complete Create  Root category And Website, store, store view then process  again. Open index.php in magento  Root Folder some changes Doc file according.
First,  Find this line code and replace.
Find  = $mageFilename = MAGENTO_ROOT . '/app/Mage.php';
Replace = $mageFilename = MAGENTO_ROOT . '../app/Mage.php';





Second ,  Find this line code and replace.
Find  =  Mage::run($mageRunCode, $mageRunType);
Replace  =

$i=$_SERVER['REQUEST_URI'];
switch ($i):
    case 'www.domain1.com':
         Mage::run("domain1","website");
        break;
    case 'www.domain2.com':
         Mage::run("domain2","website");
        break;
    case 'www.domain3.com':
         Mage::run("domain3","website");
        break;
    default:
       Mage::run("default","website");
endswitch;
 multi.JPG

After Completed two major change save index.php file in root folder. Delete all cache and Re-indexing admin panel. After restart apache server. Then check our Multi-domain website is ready for running.
Magento’s provide  powerful multi-store functionality . I hope this instruction  will provide a good starting point to help you get there!

End .

 Important Link Multi-Store & Multi Web-Site

How to make active class in magento

 Make a class in css like .mainmenu li.active a{ color:#f68e1e; }


<li class="home<?php if (Mage::helper('core/url')->getCurrentUrl() === Mage::helper('core/url')->getHomeUrl()):?> active<?php endif;?>"> <a href="<?php echo $this->getUrl('') ?>">  Home </a> </li>
     <li class="<?php if (strpos(Mage::helper('core/url')->getCurrentUrl(),'about-us') != false ) :?> active<?php endif;?>">
          <a href="<?php echo $this->getUrl('') . 'about-us' ?>"><?php echo $this->__('About Us')  ?></a>
    </li>
   <li class="<?php if (strpos(Mage::helper('core/url')->getCurrentUrl(),'product') != false ) :?> active<?php endif;?>">
          <a href="<?php echo $this->getUrl('') . 'product' ?>"><?php echo $this->__('Product')  ?></a>
    </li>



<?php if (strpos($_SERVER['REQUEST_URI'],'index') != false )
  {
  echo 'active';
  } ?>

How To Remove Please Select From Custom Option Drop Down In Magento


Open: \app\code\core\Mage\Catalog\Block\Product\View\Options\Type\Select.php Alter the following lines:
            if ($_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_DROP_DOWN) {
            $select->setName('options['.$_option->getid().']')
                ->addOption('', $this->__('-- Please Select --'));
        }

To:
            if ($_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_DROP_DOWN) {
            $select->setName('options['.$_option->getid().']');
          //      ->addOption('', $this->__('-- Please Select --'))
        }
 
Summary of changes: I commented out the ->addOption line with two 
forward slashes AND - and this is important - I moved the semi-colon 
from the end of that line to the end of the previous line.  Reversing 
this change allows you to undo the changes you made.

Magento: Add a custom State / Province / Region to a Country

 Add North and South Island to New Zealand

So let’s say that like me, you live in New Zealand and want to add 2 regions: North Island and South Island. The country id for New Zealand is NZ, the region code is a unique identifier so I’m going with NORTH and at the moment I’m only interested in the en_US locale.
First I will insert North Island into directory_country_region as follows:

INSERT INTO `directory_country_region` 
(`region_id`,`country_id`,`code`,`default_name`) 
VALUES (NULL,'NZ','NORTH','North Island');
 
Note the NULL entry for the region_id field which will auto_increment. I need to find out this new region_id for my next insert so I can either browse the table manually, or this query will do the trick:

SELECT * FROM `directory_country_region` 
WHERE `country_id`='NZ' AND`code`='NORTH' AND `default_name`='North Island';
In my case, the new region_id is 320, so with that I’ll now insert into directory_country_region_name as follows:

INSERT INTO `directory_country_region_name` 
(`locale`,`region_id`,`name`) 
VALUES ('en_US','320','North Island');
 
Now I just repeat those steps for South Island and I’m all set.

How To Add Custom Module in Magento Backend.

Step 1: Declare your shell module and it’s code pool
Create an xml file /app/etc/modules/Company_Web.xml (You can use any name, even you can use a single file to declare number of modules).
<?xml version="1.0"?>
<config>
    <modules>
        <Company_Web>
            <active>true</active>
            <codePool>local</codePool>
        </Company_Web>
    </modules>
</config> 

Step 2:
Create the basic directory structure under /app/code/core/local/ :-
Company/
|–Web/
| |–Block/
| |–controllers/
| |–etc/
| |–Helper/
| |–sql/
|

Step 3:
Write the front controller in app\code\local\Company\Web\controllers\IndexController.php
<?php
class Company_Web_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
  $this->loadLayout();     
  $this->renderLayout();
    }
}

Step 4:
Write your backend module controller in app\code\local\Company\Web\controllers\Adminhtml\WebController.php
<<?php

class Company_Web_Adminhtml_WebController extends Mage_Adminhtml_Controller_action
{

 protected function _initAction() {
  $this->loadLayout()
   ->_setActiveMenu('web/items')
   ->_addBreadcrumb(Mage::helper('adminhtml')->__('Items Manager'), Mage::helper('adminhtml')->__('Item Manager'));
  
  return $this;
 }   
 
 public function indexAction() {
  $this->_initAction()
   ->renderLayout();
 }

 public function editAction() {
  $id     = $this->getRequest()->getParam('id');
  $model  = Mage::getModel('web/web')->load($id);

  if ($model->getId() || $id == 0) {
   $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
   if (!empty($data)) {
    $model->setData($data);
   }

   Mage::register('web_data', $model);

   $this->loadLayout();
   $this->_setActiveMenu('web/items');

   $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
   $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));

   $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

   $this->_addContent($this->getLayout()->createBlock('web/adminhtml_web_edit'))
    ->_addLeft($this->getLayout()->createBlock('web/adminhtml_web_edit_tabs'));

   $this->renderLayout();
  } else {
   Mage::getSingleton('adminhtml/session')->addError(Mage::helper('web')->__('Item does not exist'));
   $this->_redirect('*/*/');
  }
 }
 
 public function newAction() {
  $this->_forward('edit');
 }
 
 public function saveAction() {
  if ($data = $this->getRequest()->getPost()) {
   
   if(isset($_FILES['filename']['name']) && $_FILES['filename']['name'] != '') {
    try { 
     /* Starting upload */ 
     $uploader = new Varien_File_Uploader('filename');
     
     // Any extention would work
              $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
     $uploader->setAllowRenameFiles(false);
     
     // Set the file upload mode 
     // false -> get the file directly in the specified folder
     // true -> get the file in the product like folders 
     // (file.jpg will go in something like /media/f/i/file.jpg)
     $uploader->setFilesDispersion(false);
       
     // We set media as the upload dir
     $path = Mage::getBaseDir('media') . DS ;
     $uploader->save($path, $_FILES['filename']['name'] );
     
    } catch (Exception $e) {
        
          }
         
          //this way the name is saved in DB
      $data['filename'] = $_FILES['filename']['name'];
   }
      
      
   $model = Mage::getModel('web/web');  
   $model->setData($data)
    ->setId($this->getRequest()->getParam('id'));
   
   try {
    if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
     $model->setCreatedTime(now())
      ->setUpdateTime(now());
    } else {
     $model->setUpdateTime(now());
    } 
    
    $model->save();
    Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('web')->__('Item was successfully saved'));
    Mage::getSingleton('adminhtml/session')->setFormData(false);

    if ($this->getRequest()->getParam('back')) {
     $this->_redirect('*/*/edit', array('id' => $model->getId()));
     return;
    }
    $this->_redirect('*/*/');
    return;
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                Mage::getSingleton('adminhtml/session')->setFormData($data);
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                return;
            }
        }
        Mage::getSingleton('adminhtml/session')->addError(Mage::helper('web')->__('Unable to find item to save'));
        $this->_redirect('*/*/');
 }
 
 public function deleteAction() {
  if( $this->getRequest()->getParam('id') > 0 ) {
   try {
    $model = Mage::getModel('web/web');
     
    $model->setId($this->getRequest()->getParam('id'))
     ->delete();
      
    Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully deleted'));
    $this->_redirect('*/*/');
   } catch (Exception $e) {
    Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
    $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
   }
  }
  $this->_redirect('*/*/');
 }

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

Step 5:
Write the frontend block file in app\code\local\Company\Web\Block\Web.php
<?php
class Company_Web_Block_Web extends Mage_Core_Block_Template
{
 public function _prepareLayout()
    {
  return parent::_prepareLayout();
    }
    
     public function getWeb()     
     { 
        if (!$this->hasData('web')) {
            $this->setData('web', Mage::registry('web'));
        }
        return $this->getData('web');
        
    }
}

Step 6: Now write the following file- app\code\local\Company\Web\Block\Adminhtml\Web.php
<?php
class Company_Web_Block_Adminhtml_Web extends Mage_Adminhtml_Block_Widget_Grid_Container
{
  public function __construct()
  {
    $this->_controller = 'adminhtml_web';
    $this->_blockGroup = 'web';
    $this->_headerText = Mage::helper('web')->__('Item Manager');
    $this->_addButtonLabel = Mage::helper('web')->__('Add Item');
    parent::__construct();
  }
}


Step 7: Now write the following file- app\code\local\Company\Web\Block\Adminhtml\Web\Grid.php
<?php

class Company_Web_Block_Adminhtml_Web_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
  public function __construct()
  {
      parent::__construct();
      $this->setId('webGrid');
      $this->setDefaultSort('web_id');
      $this->setDefaultDir('ASC');
      $this->setSaveParametersInSession(true);
  }

  protected function _prepareCollection()
  {
      $collection = Mage::getModel('web/web')->getCollection();
      $this->setCollection($collection);
      return parent::_prepareCollection();
  }

  protected function _prepareColumns()
  {
      $this->addColumn('web_id', array(
          'header'    => Mage::helper('web')->__('ID'),
          'align'     =>'right',
          'width'     => '50px',
          'index'     => 'web_id',
      ));

      $this->addColumn('title', array(
          'header'    => Mage::helper('web')->__('Title'),
          'align'     =>'left',
          'index'     => 'title',
      ));

   /*
      $this->addColumn('content', array(
   'header'    => Mage::helper('web')->__('Item Content'),
   'width'     => '150px',
   'index'     => 'content',
      ));
   */

      $this->addColumn('status', array(
          'header'    => Mage::helper('web')->__('Status'),
          'align'     => 'left',
          'width'     => '80px',
          'index'     => 'status',
          'type'      => 'options',
          'options'   => array(
              1 => 'Enabled',
              2 => 'Disabled',
          ),
      ));
   
        $this->addColumn('action',
            array(
                'header'    =>  Mage::helper('web')->__('Action'),
                'width'     => '100',
                'type'      => 'action',
                'getter'    => 'getId',
                'actions'   => array(
                    array(
                        'caption'   => Mage::helper('web')->__('Edit'),
                        'url'       => array('base'=> '*/*/edit'),
                        'field'     => 'id'
                    )
                ),
                'filter'    => false,
                'sortable'  => false,
                'index'     => 'stores',
                'is_system' => true,
        ));
  
  $this->addExportType('*/*/exportCsv', Mage::helper('web')->__('CSV'));
  $this->addExportType('*/*/exportXml', Mage::helper('web')->__('XML'));
   
      return parent::_prepareColumns();
  }

    protected function _prepareMassaction()
    {
        $this->setMassactionIdField('web_id');
        $this->getMassactionBlock()->setFormFieldName('web');

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

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

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

  public function getRowUrl($row)
  {
      return $this->getUrl('*/*/edit', array('id' => $row->getId()));
  }

}

Step 8: Now write the following file- app\code\local\Company\Web\Block\Adminhtml\Web\Edit.php
<php
class Company_Web_Block_Adminhtml_Web_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
    public function __construct()
    {
        parent::__construct();
                 
        $this->_objectId = 'id';
        $this->_blockGroup = 'web';
        $this->_controller = 'adminhtml_web';
        
        $this->_updateButton('save', 'label', Mage::helper('web')->__('Save Item'));
        $this->_updateButton('delete', 'label', Mage::helper('web')->__('Delete Item'));
  
        $this->_addButton('saveandcontinue', array(
            'label'     => Mage::helper('adminhtml')->__('Save And Continue Edit'),
            'onclick'   => 'saveAndContinueEdit()',
            'class'     => 'save',
        ), -100);

        $this->_formScripts[] = "
            function toggleEditor() {
                if (tinyMCE.getInstanceById('web_content') == null) {
                    tinyMCE.execCommand('mceAddControl', false, 'web_content');
                } else {
                    tinyMCE.execCommand('mceRemoveControl', false, 'web_content');
                }
            }

            function saveAndContinueEdit(){
                editForm.submit($('edit_form').action+'back/edit/');
            }
        ";
    }

    public function getHeaderText()
    {
        if( Mage::registry('web_data') && Mage::registry('web_data')->getId() ) {
            return Mage::helper('web')->__("Edit Item '%s'", $this->htmlEscape(Mage::registry('web_data')->getTitle()));
        } else {
            return Mage::helper('web')->__('Add Item');
        }
    }
}
Step 9:
Create the config file as app\code\local\Company\Web\etc\config.xml
<?xml version="1.0"?>
<config>
    <modules>
        <Company_Web>
            <version>0.1.0</version>
        </Company_Web>
    </modules>
    <frontend>
        <routers>
            <web>
                <use>standard</use>
                <args>
                    <module>Company_Web</module>
                    <frontName>web</frontName>
                </args>
            </web>
        </routers>
        <layout>
            <updates>
                <web>
                    <file>web.xml</file>
                </web>
            </updates>
        </layout>
    </frontend>
    <admin>
        <routers>
   <web>
    <use>admin</use>
    <args>
     <module>Company_Web</module>
     <frontName>web</frontName>
    </args>
   </web>
        </routers>
    </admin>
    <adminhtml>
  <menu>
   <web module="web">
    <title>Web</title>
    <sort_order>71</sort_order>               
    <children>
     <items module="web">
      <title>Manage Items</title>
      <sort_order>0</sort_order>
      <action>web/adminhtml_web</action>
     </items>
    </children>
   </web>
  </menu>
  <acl>
   <resources>
    <all>
     <title>Allow Everything</title>
    </all>
    <admin>
     <children>
      <Company_Web>
       <title>Web Module</title>
       <sort_order>10</sort_order>
      </Company_Web>
     </children>
    </admin>
   </resources>
  </acl>
  <layout>
   <updates>
    <web>
     <file>web.xml</file>
    </web>
   </updates>
  </layout>
    </adminhtml>   
    <global>
        <models>
            <web>
                <class>Company_Web_Model</class>
                <resourceModel>web_mysql4</resourceModel>
            </web>
            <web_mysql4>
                <class>Company_Web_Model_Mysql4</class>
                <entities>
                    <web>
                        <table>web</table>
                    </web>
                </entities>
            </web_mysql4>
        </models>
        <resources>
            <web_setup>
                <setup>
                    <module>Company_Web</module>
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </web_setup>
            <web_write>
                <connection>
                    <use>core_write</use>
                </connection>
            </web_write>
            <web_read>
                <connection>
                    <use>core_read</use>
                </connection>
            </web_read>
        </resources>
        <blocks>
            <web>
                <class>Company_Web_Block</class>
            </web>
        </blocks>
        <helpers>
            <web>
                <class>Company_Web_Helper</class>
            </web>
        </helpers>
    </global>
</config>


Step 10: Now write the helper class app\code\local\Company\Web\Helper\Data.php
<?php

class Company_Web_Helper_Data extends Mage_Core_Helper_Abstract
{

}

Step 11: Create the model class for your module app\code\local\Company\Web\Model\Web.php
<?php

class Company_Web_Model_Web extends Mage_Core_Model_Abstract
{
    public function _construct()
    {
        parent::_construct();
        $this->_init('web/web');
    }
}

Step 12: Now create app\code\local\Company\Web\Model\Mysql4\Web.php
<?php
class Company_Web_Model_Mysql4_Web extends Mage_Core_Model_Mysql4_Abstract
{
    public function _construct()
    {    
        // Note that the web_id refers to the key field in your database table.
        $this->_init('web/web', 'web_id');
    }
}

Step 13: Now create the collection class app\code\local\Company\Web\Model\Mysql4\Web\Collection.php
<?php

class Company_Web_Model_Mysql4_Web_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
    public function _construct()
    {
        parent::_construct();
        $this->_init('web/web');
    }
}

Step 14: Now add the mysql setup file as app\code\local\Company\Web\sql\web_setup\mysql4-install-0.1.0.php
<?php

$installer = $this;

$installer->startSetup();

$installer->run("

-- DROP TABLE IF EXISTS {$this->getTable('web')};
CREATE TABLE {$this->getTable('web')} (
  `web_id` int(11) unsigned NOT NULL auto_increment,
  `title` varchar(255) NOT NULL default '',
  `filename` varchar(255) NOT NULL default '',
  `content` text NOT NULL default '',
  `status` smallint(6) NOT NULL default '0',
  `created_time` datetime NULL,
  `update_time` datetime NULL,
  PRIMARY KEY (`web_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    ");

$installer->endSetup(); 

Step 15: Add the layout.xml as app\design\frontend\default\default\layout\web.xml
<?xml version="1.0"?>
<layout version="0.1.0">
    <default>
    </default>
    <web_index_index>
        <reference name="content">
            <block type="web/web" name="web" template="web/web.phtml" />
        </reference>
    </web_index_index>
</layout> 

Step 16: Now write the following file- app\design\adminhtml\default\default\layout\web.xml
<<?xml version="1.0"?>
<layout version="0.1.0">
    <web_adminhtml_web_index>
        <reference name="content">
            <block type="web/adminhtml_web" name="web" />
        </reference>
    </web_adminhtml_web_index>
</layout>

Step 17: Finally create the template file of your module app\design\frontend\default\default\template\web\web.phtml
<table border="0" cellpadding="10" cellspacing="10" width="100%">
<tr><td colspan="5" align="center"><h1>Custom Module In Magento </h1></td></tr>
<?php
//$w = Mage::getSingleton('core/resource')->getConnection('core_write');

$resource   = Mage::getSingleton('core/resource');
$conn       = $resource->getConnection('externaldb_read');
$results    = $conn->query('SELECT * FROM web');
// print_r($results)
//$row = $results->fetch(PDO::FETCH_ASSOC);
$i=1;
while ($row = $results->fetch(PDO::FETCH_ASSOC))
{ ?>
<tr>
<td><p><img src="<?php echo $this->getUrl('media/')  ?><?php echo $row['filename']; ?>" style="float:left; margin:10px;" width="100" height="100" />
<strong>Name  = <?php echo ucwords($row['title']); ?></strong> <br/>
<strong>Description :- </strong>
<?php echo $row['content']; ?>
</p>
</td>
</tr>   
<?php } ?>
</table>

How To Add Multiple Language In Magento

  • Step 1: Create two stores
    In admin section, go to System menu ->Manage Store then create two stores.
  • Step 2: Select language for each store
    In admin section, go to System menu -> Configuration. Please select each store in the top left corner, then you can select a language for that store in locale dropdown.
  • Step 3: Create locale package for each language
    Create two folders: en_US and fr_FR in app/locale folder
Now you can go to the front-end and see how it works.

Tuesday, 4 September 2012

How To Show In Stock And Out Stock Product in Magento

 isSaleable()): ?>
           
__('Out Of Stock') ?>

       
           
__('In Stock') ?>

       

Saturday, 1 September 2012

Create Your First Admin (Backend) Module in Magento

Namespace : Company

Module Name : Web




Step 1: Declare your shell module and it’s code pool
Create an xml file /app/etc/modules/Company_Web.xml (You can use any name, even you can use a single file to declare number of modules).

    
        
            true
            local
        
    
 

Step 2:
Create the basic directory structure under /app/code/core/local/ :-
Company/
|–Web/
| |–Block/
| |–controllers/
| |–etc/
| |–Helper/
| |–sql/
|

Step 3:
Write the front controller in app\code\local\Company\Web\controllers\IndexController.php
loadLayout();     
  $this->renderLayout();
    }
}

Step 4:
Write your backend module controller in app\code\local\Company\Web\controllers\Adminhtml\WebController.php
<loadLayout()
   ->_setActiveMenu('web/items')
   ->_addBreadcrumb(Mage::helper('adminhtml')->__('Items Manager'), Mage::helper('adminhtml')->__('Item Manager'));
  
  return $this;
 }   
 
 public function indexAction() {
  $this->_initAction()
   ->renderLayout();
 }

 public function editAction() {
  $id     = $this->getRequest()->getParam('id');
  $model  = Mage::getModel('web/web')->load($id);

  if ($model->getId() || $id == 0) {
   $data = Mage::getSingleton('adminhtml/session')->getFormData(true);
   if (!empty($data)) {
    $model->setData($data);
   }

   Mage::register('web_data', $model);

   $this->loadLayout();
   $this->_setActiveMenu('web/items');

   $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
   $this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));

   $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

   $this->_addContent($this->getLayout()->createBlock('web/adminhtml_web_edit'))
    ->_addLeft($this->getLayout()->createBlock('web/adminhtml_web_edit_tabs'));

   $this->renderLayout();
  } else {
   Mage::getSingleton('adminhtml/session')->addError(Mage::helper('web')->__('Item does not exist'));
   $this->_redirect('*/*/');
  }
 }
 
 public function newAction() {
  $this->_forward('edit');
 }
 
 public function saveAction() {
  if ($data = $this->getRequest()->getPost()) {
   
   if(isset($_FILES['filename']['name']) && $_FILES['filename']['name'] != '') {
    try { 
     /* Starting upload */ 
     $uploader = new Varien_File_Uploader('filename');
     
     // Any extention would work
              $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
     $uploader->setAllowRenameFiles(false);
     
     // Set the file upload mode 
     // false -> get the file directly in the specified folder
     // true -> get the file in the product like folders 
     // (file.jpg will go in something like /media/f/i/file.jpg)
     $uploader->setFilesDispersion(false);
       
     // We set media as the upload dir
     $path = Mage::getBaseDir('media') . DS ;
     $uploader->save($path, $_FILES['filename']['name'] );
     
    } catch (Exception $e) {
        
          }
         
          //this way the name is saved in DB
      $data['filename'] = $_FILES['filename']['name'];
   }
      
      
   $model = Mage::getModel('web/web');  
   $model->setData($data)
    ->setId($this->getRequest()->getParam('id'));
   
   try {
    if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
     $model->setCreatedTime(now())
      ->setUpdateTime(now());
    } else {
     $model->setUpdateTime(now());
    } 
    
    $model->save();
    Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('web')->__('Item was successfully saved'));
    Mage::getSingleton('adminhtml/session')->setFormData(false);

    if ($this->getRequest()->getParam('back')) {
     $this->_redirect('*/*/edit', array('id' => $model->getId()));
     return;
    }
    $this->_redirect('*/*/');
    return;
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                Mage::getSingleton('adminhtml/session')->setFormData($data);
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                return;
            }
        }
        Mage::getSingleton('adminhtml/session')->addError(Mage::helper('web')->__('Unable to find item to save'));
        $this->_redirect('*/*/');
 }
 
 public function deleteAction() {
  if( $this->getRequest()->getParam('id') > 0 ) {
   try {
    $model = Mage::getModel('web/web');
     
    $model->setId($this->getRequest()->getParam('id'))
     ->delete();
      
    Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully deleted'));
    $this->_redirect('*/*/');
   } catch (Exception $e) {
    Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
    $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
   }
  }
  $this->_redirect('*/*/');
 }

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

Step 5:
Write the frontend block file in app\code\local\Company\Web\Block\Web.php
hasData('web')) {
            $this->setData('web', Mage::registry('web'));
        }
        return $this->getData('web');
        
    }
}

Step 6: Now write the following file- app\code\local\Company\Web\Block\Adminhtml\Web.php
_controller = 'adminhtml_web';
    $this->_blockGroup = 'web';
    $this->_headerText = Mage::helper('web')->__('Item Manager');
    $this->_addButtonLabel = Mage::helper('web')->__('Add Item');
    parent::__construct();
  }
}


Step 7: Now write the following file- app\code\local\Company\Web\Block\Adminhtml\Web\Grid.php
setId('webGrid');
      $this->setDefaultSort('web_id');
      $this->setDefaultDir('ASC');
      $this->setSaveParametersInSession(true);
  }

  protected function _prepareCollection()
  {
      $collection = Mage::getModel('web/web')->getCollection();
      $this->setCollection($collection);
      return parent::_prepareCollection();
  }

  protected function _prepareColumns()
  {
      $this->addColumn('web_id', array(
          'header'    => Mage::helper('web')->__('ID'),
          'align'     =>'right',
          'width'     => '50px',
          'index'     => 'web_id',
      ));

      $this->addColumn('title', array(
          'header'    => Mage::helper('web')->__('Title'),
          'align'     =>'left',
          'index'     => 'title',
      ));

   /*
      $this->addColumn('content', array(
   'header'    => Mage::helper('web')->__('Item Content'),
   'width'     => '150px',
   'index'     => 'content',
      ));
   */

      $this->addColumn('status', array(
          'header'    => Mage::helper('web')->__('Status'),
          'align'     => 'left',
          'width'     => '80px',
          'index'     => 'status',
          'type'      => 'options',
          'options'   => array(
              1 => 'Enabled',
              2 => 'Disabled',
          ),
      ));
   
        $this->addColumn('action',
            array(
                'header'    =>  Mage::helper('web')->__('Action'),
                'width'     => '100',
                'type'      => 'action',
                'getter'    => 'getId',
                'actions'   => array(
                    array(
                        'caption'   => Mage::helper('web')->__('Edit'),
                        'url'       => array('base'=> '*/*/edit'),
                        'field'     => 'id'
                    )
                ),
                'filter'    => false,
                'sortable'  => false,
                'index'     => 'stores',
                'is_system' => true,
        ));
  
  $this->addExportType('*/*/exportCsv', Mage::helper('web')->__('CSV'));
  $this->addExportType('*/*/exportXml', Mage::helper('web')->__('XML'));
   
      return parent::_prepareColumns();
  }

    protected function _prepareMassaction()
    {
        $this->setMassactionIdField('web_id');
        $this->getMassactionBlock()->setFormFieldName('web');

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

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

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

  public function getRowUrl($row)
  {
      return $this->getUrl('*/*/edit', array('id' => $row->getId()));
  }

}

Step 8: Now write the following file- app\code\local\Company\Web\Block\Adminhtml\Web\Edit.php
_objectId = 'id';
        $this->_blockGroup = 'web';
        $this->_controller = 'adminhtml_web';
        
        $this->_updateButton('save', 'label', Mage::helper('web')->__('Save Item'));
        $this->_updateButton('delete', 'label', Mage::helper('web')->__('Delete Item'));
  
        $this->_addButton('saveandcontinue', array(
            'label'     => Mage::helper('adminhtml')->__('Save And Continue Edit'),
            'onclick'   => 'saveAndContinueEdit()',
            'class'     => 'save',
        ), -100);

        $this->_formScripts[] = "
            function toggleEditor() {
                if (tinyMCE.getInstanceById('web_content') == null) {
                    tinyMCE.execCommand('mceAddControl', false, 'web_content');
                } else {
                    tinyMCE.execCommand('mceRemoveControl', false, 'web_content');
                }
            }

            function saveAndContinueEdit(){
                editForm.submit($('edit_form').action+'back/edit/');
            }
        ";
    }

    public function getHeaderText()
    {
        if( Mage::registry('web_data') && Mage::registry('web_data')->getId() ) {
            return Mage::helper('web')->__("Edit Item '%s'", $this->htmlEscape(Mage::registry('web_data')->getTitle()));
        } else {
            return Mage::helper('web')->__('Add Item');
        }
    }
}
Step 9:
Create the config file as app\code\local\Company\Web\etc\config.xml

    
        
            0.1.0
        
    
    
        
            
                standard
                
                    Company_Web
                    web
                
            
        
        
            
                
                    web.xml
                
            
        
    
    
        
   
    admin
    
     Company_Web
     web
    
   
        
    
    
  
   
    Web
    71               
    
     
      Manage Items
      0
      web/adminhtml_web
     
    
   
  
  
   
    
     Allow Everything
    
    
     
      
       Web Module
       10
      
     
    
   
  
  
   
    
     web.xml
    
   
  
       
    
        
            
                Company_Web_Model
                web_mysql4
            
            
                Company_Web_Model_Mysql4
                
                    
                        web
Company_Web core_setup core_write core_read Company_Web_Block Company_Web_Helper


Step 10: Now write the helper class app\code\local\Company\Web\Helper\Data.php


Step 11: Create the model class for your module app\code\local\Company\Web\Model\Web.php
_init('web/web');
    }
}
Step 12: Now create app\code\local\Company\Web\Model\Mysql4\Web.php
_init('web/web', 'web_id');
    }
}
Step 13: Now create the collection class app\code\local\Company\Web\Model\Mysql4\Web\Collection.php
_init('web/web');
    }
}
Step 14: Now add the mysql setup file as app\code\local\Company\Web\sql\web_setup\mysql4-install-0.1.0.php
startSetup();

$installer->run("

-- DROP TABLE IF EXISTS {$this->getTable('web')};
CREATE TABLE {$this->getTable('web')} (
  `web_id` int(11) unsigned NOT NULL auto_increment,
  `title` varchar(255) NOT NULL default '',
  `filename` varchar(255) NOT NULL default '',
  `content` text NOT NULL default '',
  `status` smallint(6) NOT NULL default '0',
  `created_time` datetime NULL,
  `update_time` datetime NULL,
  PRIMARY KEY (`web_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    ");

$installer->endSetup(); 
Step 15: Add the layout.xml as app\design\frontend\default\default\layout\web.xml

    
    
    
        
            
        
    
 
Step 16: Now write the following file- app\design\adminhtml\default\default\layout\web.xml
<

    
        
            
        
    
Step 17: Finally create the template file of your module app\design\frontend\default\default\template\web\web.phtml

Magento get file paths and URL

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


(A) The parameters of interest are Url:

    1.url
    2.direct_url
    3._query
    4._query_[name]

1. url :-
<a href="{{store url=""}}">Go to home page</a>
<a href="{{store url="contacts"}}">Contact Us</a>

2. direct_url :-
<a href="{{store direct_url="category/subcategory.html"}}">Our Latest Range</a>

3. _query and
<a href="{{store direct_url="category/subcategory.html" _query="a=param_a&amp;b=param_b"}}">Our Latest Range</a>

4. _query_[name] :-
<a href="{{store direct_url="category/subcategory.html" _query_a="param_a" _query_b="param_b"}}">;Our Latest Range</a>

Example :-

This results in the same URL as the previous example:
http://yourstore.com/category/subcategory.html?a=param_a&b=param_b