Category Archives: Magento

Magento

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"/> -->

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”.

Magento Set, Retrieve and Unset Session Variables

To set, retrive and unset session variables in Magento

To Set a session variable:

1
2
3
4
<?php
$sesValue = 'Hello';
Mage::getSingleton('core/session')->setSessionValue($sesValue);
?>

To Retrieve a session variable:

1
2
3
4
<?php
$sesValue = '';
$sesValue = Mage::getSingleton('core/session')->getSessionValue();
?>

To Unset:

1
2
3
<?php
Mage::getSingleton('core/session')->unsSessionValue();
?>

Note: that ‘SessionValue’ can be any text but you need to ‘set’, ‘get’ and ‘uns’ prefixes are required.

Get category image in Magento

It is a very simple and easy way to get a category image in Magento.
If you want to show the current category image in Magento, Please use following code given below:

1
2
$category = Mage::getModel('catalog/layer')->getCurrentCategory(); 
$img = $this->getCategoryImage($category); // call a function

Please create a function as given below:

1
2
3
4
5
6
7
8
9
10
11
12
13
function getCategoryImage($category) 
{
    $categoryCollection = Mage::getModel('catalog/category')
                        ->setStoreId(Mage::app()->getStore()->getId())
                        ->getCollection()
                        ->addAttributeToSelect('image')
                        ->addIdFilter($category->getId());

    foreach($categoryCollection as $category) 
    {
        return $category->getImageUrl();
    }
}

How to delete Magento order programmatically

Unfortunately, there is no way in Magento to delete the orders from Magento store.
You can only process and set status as “Cancelled” of these orders but you can’t really delete those orders from your Magento store.
In order to delete these orders, you have to log in to your PhpmyAdmin and run some queries to get rid of those orders.

Delete a single order:

You need to run the following query on your database:

1
2
3
4
set @increment_id='00000111';
select @order_id:=entity_id from prefix_sales_order_entity where increment_id=@increment_id;
delete from prefix_sales_order_entity where entity_id=@order_id or parent_id=@order_id;
delete from prefix_sales_order where increment_id=@increment_id;

In the above example, we deleted order ‘#00000111′. Generally people use prefix to database tables, so change the “prefix_” in the above query with the prefix you have chosen for your store.

Delete all Magento orders:

You need to run the following query on your database:

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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;

-- lets 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;

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

SET FOREIGN_KEY_CHECKS=1;

How to get currency code in Magento

We know Magento support multiple currency. Use following code given below to check current currency in the Magento site frontend.

To get current currency code

1
<?php echo $current_currency_code = Mage::app()->getStore()->getCurrentCurrencyCode(); ?>

If you looking for current currency symbol use :

1
<?php echo Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol(); ?>