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','[email protected]','1234567890');
insert into `sarfraz` (`id`,`first_name`,`cus_email`,`telephone`) values (2,'Joe Burton','[email protected]','5556667777');
insert into `sarfraz` (`id`,`first_name`,`cus_email`,`telephone`) values (3,'Alice Keys','[email protected]','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.

How to get the customer email address in Magento

I was recently working on a payment module for Magento and I needed to fetch the customer email address to submit it along with the other payment details.

I found a method by which I could get the email of the customer who was already registered on the website and was shopping after logging in with his/her details.

$cusemail = Mage::getSingleton('customer/session')->getCustomer()->getEmail();

However the above line returned empty in case of a first time customer. So I modified the code as follows

$cusemail = Mage::getSingleton('customer/session')->getCustomer()->getEmail();

if (strlen($cusemail) > 0) {
	// Do nothing
}
else {
	//Get the current order details in a $order variable and fetch the customer email from there 
	$cusemail = $order['customer_email'];	
}

Hope the above helped.

An alternative way to check mySQL version in the Magento check script

Magento, like most other open source softwares, provides a list of requirements which need to be fulfilled before it can be installed on your machine. If you are installing Magento for the first time then I would recommend that you read the server requirments. on the other hand there may be some who would like to know which server requirements are fulfilled by their server so that they can see at a glance what they need to ask their hosting providers to install/setup for them.

Magento provides a script for this purpose which can be viewed on this page. You can download the actual script from here. Unzip the downloaded zip file and you will see a PHP script. Copy the script to the location where you would like to install Magento and execute it.

Once executed you will see the output on the page as follows:

The above snap shot shows that the mySQL version installed does not fulfill the version which is funny as we have mySQL community version 5.1 installed which is more than what is required. I looked through the code and found the following code on line 30 which checks the mySQL version

preg_match('/[0-9]\.[0-9]+\.[0-9]+/', shell_exec('mysql -V'), $version);

Note:The shell_exec() command is not allowed on shared hosting servers as it could allow a coder to run code which may compromise the security and stability of the server.

This could be the reason why the $version was coming up empty and due to this the script was flagging that the mySQL version was incompatible. The shell_exec() command may run correctly on some computers but it did not run as expected on ours so I thought of altering it to show the correct mySQL version.

mySQL provides a function mysql_get_server_info() which returns the mySQL version number. The only thing it needs is a connection to be opened to mySQL so it could then return the information. I commented out line 30 and added the following lines of code:

$conn = mysql_connect('server','username','password');
preg_match('/[0-9]\.[0-9]+\.[0-9]+/', mysql_get_server_info(), $version);

You should know the details to connect to your mySQL server for the above to work. After making the above changes I ran the script again and this time it gave the following output:

Please note that the shell_exec() is not wrong but it does not work on some servers due to restrictions. The method I have provided is a workaround should the first method not work.

Comments?

How to setup Magento store on your PC

If you going to start working on Magento (e-commerce package) then you can do the following steps and you will have your store ready in a jiffy.

1. First download the Magento e-commerce software from

http://www.magentocommerce.com

2. Click on Download and you will be taken to

http://www.magentocommerce.com/download

3. If you would like to register on the website then you can fill in the form. This will also help you to post questions on their forums should you require any help. As this post is mostly concerned with setting up your store then you can just click on “No thanks, take me to the download page”.

4. You will find several download options. We are concerned with the Full Installer here. Select the download file from the drop down and click on Download.

5. Please remember to make sure that your system fulfills the prerequisites mentioned on the following page:

http://www.magentocommerce.com/system-requirements

6. Once the above steps are complete, you can start by opening the index.php file at the root and add the following line at the start of the file

set_time_limit(0);

7. This step is not necessary however on some systems I have seen that Magento takes a long time installing the database due to which script time out may occur. Magento has commented out DROP TABLE lines in the SQL that is executed while installation. So, it’s a good idea to do a Find-Replace as follows

Find : — DROP TABLE

Replace with : DROP TABLE

8. Now, you can run the index.php file in the browser and the installation process will start. You will be asked database related information, admin user information etc. which you can enter easily. The whole process will be complete in a couple of minutes and then you can browse your store.

9. On some local systems you may have a problem in logging into the admin panel. You can find the fix here

http://www.magentocommerce.com/boards/viewthread/50451/

Hope the above helped. If you need any sort of help then do let me know.