Tutorial to create custom Magento module

I could not find one good tutorial on developing a custom module in Magento when I had a client requirement to develop one for his website. It was not like there weren’t any. If you Google “custom Magento module tutorial” or something similar you will get a lot of search results however I received a lot of errors when I tried using them in my case. Either they were not tested or they were not supposed to work in that way but I am not complaining as it helped me to learn more about Magento and custom module development in Magento.

Follow the steps below to create your first custom Magento module. This module will display entries from a database table and display it in the Magento admin panel. I have tested this module on Magento community versions 1.6.2 and 1.7.0 and it is working on both of them.

Run the following SQL statement in your mySQL database.

CREATE TABLE `sarfraz` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(100) DEFAULT NULL,
  `cus_email` varchar(100) DEFAULT NULL,
  `telephone` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

After running the above statement it should create a table by the name of “sarfraz” in your database. Now run the following insert SQL statements to create records in the table.

insert into `sarfraz` (`id`,`first_name`,`cus_email`,`telephone`) values (1,'Adam Sandler','adam@example.com','1234567890');
insert into `sarfraz` (`id`,`first_name`,`cus_email`,`telephone`) values (2,'Joe Burton','joe@example.com','5556667777');
insert into `sarfraz` (`id`,`first_name`,`cus_email`,`telephone`) values (3,'Alice Keys','alice@example.com','66677788888');

Our table now has some entries so we can now proceed with the actual coding related changes.

First create your XML file in the app/etc/modules folder. In this tutotial my XML file is named as Adeel_Sarfraz.xml however you are free to choose what ever name is right for you.

<?xml version="1.0"?>
<config>
    <modules>
        <Adeel_Sarfraz>
            <active>true</active>
            <codePool>local</codePool>
            <version>1.0.0</version>
        </Adeel_Sarfraz>
    </modules>
</config>

The above code will register your module in Magento. Now we put in the actual code for the module.

Go to app/code/local folder and create a new folder by the name of “Adeel” and then create another folder within it by the name of “Sarfraz”.

Now create 5 folders in the app/etc/local/Adeel/Sarfraz folder.

1. Block
2. controllers
3. etc
4. Helper
5. Model

We will start now by creating a config.xml file in the etc folder. Once you have created it you can add the following code to the config.xml file.

<?xml version="1.0"?>
<config>

    <modules>
        <Adeel_Sarfraz>
            <version>1.0.0</version>
        </Adeel_Sarfraz>
    </modules>
	
	<global>
	
		<helpers>
			<sarfraz>
				<class>Adeel_Sarfraz_Helper</class>
			</sarfraz>
		</helpers>

        <models>
            <sarfraz>
                <class>Adeel_Sarfraz_Model</class>
                <resourceModel>sarfraz_mysql4</resourceModel>
            </sarfraz>
            <sarfraz_mysql4>
                <class>Adeel_Sarfraz_Model_Mysql4</class>
                <entities>
                    <sarfraz>
                        <table>sarfraz</table>
                    </sarfraz>
                </entities>
            </sarfraz_mysql4>
        </models>		
		
		<blocks>
			<sarfraz>
				<class>Adeel_Sarfraz_Block</class>
			</sarfraz>
		</blocks>		
	
	</global>	
	
    <admin>
        <routers>
            <asarfraz>
                <use>admin</use>
                <args>
                    <module>Adeel_Sarfraz</module>
                    <frontName>asarfraz</frontName>
                </args>
            </asarfraz>
        </routers>
    </admin>
	
    <adminhtml>
        <menu>
            <customer>
                <children>
                    <list translate="title" module="sarfraz">
                        <title>Admin Title</title>
                        <sort_order>11</sort_order>
			<action>asarfraz/controller_list/index</action>
                    </list>
                </children>
            </customer>
        </menu>
    </adminhtml>
	
</config>

1. Now add the following folders and files in the Block folder.

Adminhtml
Adminhtml/Items
Adminhtml/Items.php
Adminhtml/Items/Grid.php

Open the Block/Adminhtml/Items.php and add the following PHP code to it.

<?php
class Adeel_Sarfraz_Block_Adminhtml_Items extends Mage_Adminhtml_Block_Widget_Grid_Container
{
    public function __construct()
    {
        $this->_controller = 'adminhtml_items';
        $this->_blockGroup = 'sarfraz';		
        $this->_headerText = Mage::helper('sarfraz')->__('Admin Title');
        parent::__construct();				
        $this->_removeButton('add');		
    }
}

Next open the Block/Adminhtml/Items/Grid.php and add the following PHP code to it.

<?php
class Adeel_Sarfraz_Block_Adminhtml_Items_Grid extends Mage_Adminhtml_Block_Widget_Grid
{	
    public function __construct()
    {
		
        parent::__construct();
        $this->setId('itemsGrid');
        $this->setDefaultSort('id');
		$this->setDefaultDir('DESC');		
    }
 
    protected function _prepareCollection()
    {
        $collection = Mage::getModel('sarfraz/sarfraz')->getCollection();
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }
 
    protected function _prepareColumns()
    {
        $this->addColumn('id', array(
            'header' => Mage::helper('sarfraz')->__('ID'),
            'sortable' => true,
            'width' => '60',
            'index' => 'id'
        ));
 
        $this->addColumn('first_name', array(
            'header' => Mage::helper('sarfraz')->__('Full Name'),
            'sortable' => true,
            'width' => '60',
            'index' => 'first_name',
            'type'  => 'text'
        ));
 
        $this->addColumn('cus_email', array(
            'header' => Mage::helper('sarfraz')->__('Email Address'),
            'sortable' => true,
            'width' => '60',
            'index' => 'cus_email',
            'type'  => 'text'
        ));

		$this->addColumn('telephone', array(
            'header' => Mage::helper('sarfraz')->__('Answer'),
            'sortable' => true,
            'width' => '60',
            'index' => 'cus_telephone',
            'type'  => 'text'
        ));				

		return parent::_prepareColumns();
    }
 
}

2. Add the following folder and file to the controllers folder

Controller
Controller/ListController.php

Open the controllers/Controller/ListController.php file and add the following PHP code

<?php
class Adeel_Sarfraz_Controller_ListController extends Mage_Adminhtml_Controller_Action
{
    public function indexAction()
    { 
        $this->loadLayout()->_setActiveMenu('customers');
        $myblock = $this->_addContent($this->getLayout()->createBlock('sarfraz/adminhtml_items'));
        $this->renderLayout($myblock);
    }
}

3. Create the following file in the Helper folder.

Data.php

Add the following PHP code to Data.php file

<?php
class Adeel_Sarfraz_Helper_Data extends Mage_Core_Helper_Abstract
{

}

4. Add the following files and folders to the Model folder

Mysql4
Sarfraz.php
Mysql4/Sarfraz
Mysql4/Sarfraz.php
Mysql4/Sarfraz/Collection.php

Open the Model/Sarfraz.php file and add the following code

<?php
class Adeel_Sarfraz_Model_Sarfraz extends Mage_Core_Model_Abstract
{
    public function _construct()
    {
       parent::_construct();
       $this->_init('sarfraz/sarfraz');
    }
}

Then open the Model/Mysql4/Sarfraz.php file and add the following code

<?php
class Adeel_Sarfraz_Model_Mysql4_Sarfraz extends Mage_Core_Model_Mysql4_Abstract
{
    public function _construct()
    {   
        $this->_init('sarfraz/sarfraz', 'id');
    }
}

Finally open the Model/Mysql4/Sarfraz/Collection.php and add the code below

<?php
class Adeel_Sarfraz_Model_Mysql4_Sarfraz_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
    public function _construct()
    {
	parent::_construct();
        $this->_init('sarfraz/sarfraz');
    }
}

After adding the code changes above please clear the Magento cache and your module should come up under the customers menu by the name of “Admin Title”. If it does’t then logout and relogin into the Magento admin panel. You can change the “Admin Title” to some thing more meaningful by editing the etc/config.xml file.

If the above is too much time consuming for you then you can contact me and I will provide you the files in zip format.

If you have any feedback then please share by commenting.

Leave a Reply