Get Store and Website information in Magento

Many a time it requires a programmer to access the store information like store id or store status, store name, website id, website name etc.

These methods will help to fetch the details of the current store and website in Magento.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*Get Store*/
echo Mage::app()->getStore();

/*Store Id*/
echo Mage::app()->getStore()->getStoreId();

/*Store Name*/
echo Mage::app()->getStore()->getName();

/*Store code*/
echo Mage::app()->getStore()->getCode();

/*Store is Active*/
echo Mage::app()->getStore()->getIsActive();

/*Store Home Url*/
echo Mage::app()->getStore()->getHomeUrl();

/*Website Id*/
echo Mage::app()->getStore()->getWebsiteId();

/*Website Name*/
echo Mage::app()->getStore()->getWebsiteName();

Hope! it will help.

How to use multiple database tables in single custom module in Magento

Creating a module which interact with a database table is quite simple. Most of the developers use magento module creator to create such module. But what if you want a module with multiple database tables. Following is the example of module with two database tables.

Step 1. Create setup file of your custom module with following queries.

1
2
3
4
5
6
7
8
9
CREATE TABLE `test` (
`test_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 25 ) NOT NULL
) ENGINE = MYISAM 

CREATE TABLE `test2` (
`test2_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 25 ) NOT NULL
) ENGINE = MYISAM

Step 2. Create pool file to register your module under app/etc/modules/Mypackage_Mymodule.xml

1
2
3
4
5
6
7
8
9
<?xml version="1.0"?>
<config>
    <modules>
        <Mypackage_Mymodule>
            <active>true</active>
            <codePool>local</codePool>
        </Mypackage_Mymodule>
    </modules>
</config>

Step 3. Your module configuration file should looks like following

app/code/local/ Mypackage/Mymodule/etc/config.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?xml version="1.0"?>
<config>
    <modules>
        <Mypackage_Mymodule>
            <version>0.1.0</version>
        </Mypackage_Mymodule>
    </modules>
    <global>
        <models>
            <Mymodule>
                <class>Mypackage_Mymodule_Model</class>
                <resourceModel>mymodule_mysql4</resourceModel>
            </mymodule>
            
            <!-- model vs db table relation -->
            <mymodule_mysql4>
                <class>Mypackage_Mymodule_Model_Mysql4</class>
                <!-- db table with name test -->
                <entities>
                    <test>
                        <table>test</table>
                    </test>
             <test2>
                        <table>test2</table>
                    </test2>

                </entities>
            </mymodule_mysql4>
        </models>
        <resources>
            <mymodule_write>
                <connection>
                    <use>core_write</use>
                </connection>
            </mymodule_write>
            <mymodule_read>
                <connection>
                    <use>core_read</use>
                </connection>
            </mymodule_read>
        </resources>
    </global>
</config>

Step 4. Now create models Test.php and Test2.php. Here we configure these model with the handler of table test and test2.

/app/code/local/Mypackage/Mymodule/Model/Test.php

1
2
3
4
5
6
7
8
9
10
11
<?php

class Mypackage_ Mymodule_Model_Test extends Mage_Core_Model_Abstract
{
    
    public function _construct()
    {
        parent::_construct();
        $this->_init('mymodule/test');
    }
}

/app/code/local/Mypackage/Mymodule/Model/Test2.php

1
2
3
4
5
6
7
8
9
10
11
<?php

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

Step 5. Now create the resource models for model test and test2. In these files we also set the primary key of both the tables test and test2.

/app/code/local/Mypackage/Mmodule/Model/Mysql4/Test.php

1
2
3
4
5
6
7
8
9
<?php

class Mypackage_Mymodule_Model_Mysql4_Test extends Mage_Core_Model_Mysql4_Abstract
{
    public function _construct()
    {    
        $this->_init('mymodule/test', 'test_id');
    }
}

/app/code/local/Mypackage/Mmodule/Model/Mysql4/Test2.php.

1
2
3
4
5
6
7
8
9
<?php

class Mypackage_Mymodule_Model_Mysql4_Test2 extends Mage_Core_Model_Mysql4_Abstract
{
    public function _construct()
    {    
        $this->_init('mymodule/test2', 'test2_id');
    }
}

Step 6. Create a collection classes so that we can retrieve data from table test and test2.

/local/Mypackage/Mymodule/Model/Mysql4/Test/Collection.php

1
2
3
4
5
6
7
8
9
10
<?php

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

/local/Mypackage/Mymodule/Model/Mysql4/Test2/Collection.php

1
2
3
4
5
6
7
8
9
10
<?php

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

So, now you have a custom module with two tables. Your module can interact with these tables with their models and respective collections as follows :

1
2
3
4
5
6
7
$testModel = Mage::getModel('mymodule/test')
    ->setName("abcd")
    ->save();

$test2Model = Mage::getModel('mymodule/test2')
    ->setName("abcd")
    ->save();

Hope this will help you.

Magento filter collection codes

A collection is a Model type containing other Models, it is basically used in Magento to handle product lists (ie. from a category or a bundle option), but not only. Please use following collection filter code in magento:

Magento filter collection codes

Magento filter collection codes

Get all disabled products programmatically in Magento

Get all disabled products from Magento using product collection:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
set_time_limit(0);
error_reporting(E_ALL ^ E_NOTICE);
ini_set("display_errors",'On');

require_once 'app/Mage.php';
umask(0);
Mage::app('default');

$products = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('*')
    ->addFieldToFilter('status',Mage_Catalog_Model_Product_Status::STATUS_DISABLED);

$products->load();
foreach($products as $product) {
    echo $product->getData('sku')."<br />";
    //var_dump($product->getStatus());
}
?>

Get all disabled products from Magento using Database SQL query:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
set_time_limit(0);
error_reporting(E_ALL ^ E_NOTICE);
ini_set("display_errors",'On');

require_once 'app/Mage.php';
umask(0);
Mage::app('default');
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

$conn = Mage::getSingleton('core/resource')->getConnection('core_write');

$catSQL = "SELECT *
FROM `itshot_catalog_product_entity_int`
WHERE `attribute_id` =84  // status=84 (see status id from attributes)
AND `value` =2  // disabled value=2
//AND `entity_id` >30970"; // if you want to show result from range
$categories = $conn->fetchAll($catSQL);
foreach ($categories as $product)
{
    $id = trim($product["entity_id"]);
}
?>

How to redirect after login to a particular page which depend upon the page from which login is clicked in magento?

By deafult, when customer/user log in Magento, he/she is redirected to its account page.

But if you’d like to redirect the customer back to the product/page he was visiting before.

1
2
3
4
5
6
7
Login to Magento Admin.

Go to System -> Configuration -> Customer Configuration -> Login Options.

From the drop-down select "no" and save configuration. 

Refresh the cache and try to login.

Hope! you will enjoy.

Disable Breadcrumbs in Magento

Go to the app/design/frontend/default/* (your current theme)/layout/ directory

Open page.xml (if not there, copy from base directory) and comment the following:

Change:

1
<block type="page/html_breadcrumbs" name="breadcrumbs" as="breadcrumbs"/>

To:

1
<!-- <block type="page/html_breadcrumbs" name="breadcrumbs" as="breadcrumbs"/> -->

How to set multiple layout in Zend FrameWork

During developing an application we need to set the multiple layout for a particular controller, action, view.

Set layout for a particular controller or action:

Within Controller/action

1
2
3
4
5
<?php   
(a) Zend_Layout::getMvcInstance()->setLayout('layout_name');
            
(b) $this->_helper->layout()->setLayout('layout-user');
?>

Within View

1
<?php $this->layout()->setLayout('layout_name'); ?>

Disable layout for a particular controller or action:

Within controller, action

1
2
3
4
<?php
$this->_helper->layout()->disableLayout(); 
$this->_helper->viewRenderer->setNoRender(true);
?>

How to set Layout using Plugin in Zend FrameWork

Some time we need to set different layout based on user type. So the best way to handle it by using plugin.

Bootstrap.php:

1
2
3
4
5
6
7
8
9
10
11
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

    public function _initPlugins()
    {
        $front = Zend_Controller_Front::getInstance();
        $front->registerPlugin(new Zend_Controller_Plugin_Acl()); // Plugin file path library/zend/controller/Plugin/Acl.php
    }
}
?>

In library/zend/controller/Plugin/Acl.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
class Zend_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch()
    {
        $user = Zend_Auth::getInstance();
        $role = $user->getIdentity()->role;
        $layout = Zend_Layout::getMvcInstance();

        switch ($role) {
            case 'admin':
                $layout->setLayout('layout1');
                break;

            case 'user':
                $layout->setLayout('layout2');
                break;

            default:
                $layout->setLayout('layout');
                break;
        }
    }
}
?>

Hope! you will enjoy.

Remove Session ID from URL in Magento

This post explains how to disable the Session ID in URLs of your Magento.
Magento adds a SID at the end of the URL by default.

magento_sid_url

Option 1 – Disable SID from Magento admin
Login to your Magento administration panel and Go to System->Configuration->Web tab.

disable_magento_sid

Option 2 – Edit App.php file
In some cases using option 1 does not work and Magento overwrites your settings. To ensure SID is disabled, you need to manually edit Magento’s App.php file. Go to app/code/core/Mage/Core/Model folder on your server and open/download the App.php file.

magento_edit_php_file

Change $_useSessionInUrl value from “true” to “false“.

Note. This value is reset to its default “true” value when Magento is upgraded. Remember to change it back to “false”.

How to create/setup custom routing in ZendFramework

Routing is the process of taking a URI endpoint (that part of the URI which comes after the base URL) and decomposing it into parameters to determine which module, controller, and action of that controller should receive the request.
In simple way, we can say that this is same as URL Rewriting in PHP we do.

Ex1 : Routing without variables

Now, say for example your domain is http://mydomain.com
And you want the http://mydomain.com/register/user to be http://mydomain.com/user-registration

Put the code below in Bootstrap.php file as

1
2
3
4
5
6
7
<?php
protected function _initRoute()
{
    $router = Zend_Controller_Front::getInstance()->getRouter(); //create object of a router
    $router->addRoute('registration',new Zend_Controller_Router_Route('user-registration',array('controller'=>'register','action'=>'user'))); //registration can be any text as you want
}
?>

Ex2 : Routing with variables

Now, say for example http://mydomain.com/product/10

Put the code below in Bootstrap.php file as

1
2
3
4
5
6
7
<?php
protected function _initRoute()
{
    $router = Zend_Controller_Front::getInstance()->getRouter(); //create object of a router
    $router->addRoute('myproduct',new Zend_Controller_Router_Route('product/:id',array('controller'=>'product','action'=>'index'))); //myproduct can be any text as you want 
}
?>

Hope, you will enjoy!