Module Development Series – Magento Admin Module – Part1

In this blog post, we will see how to set up admin pages for your module. Specifically in this blog post i will show the basic of how to set up Grid in magento.

Before reading this blog, I assume you are familiar with basics of magento module development and have used Models,Collections. Now, lets start: The name of module I am using is Excellence_Employee, so all classes will be named accordingly. Please change class name as per your module.
Note: You can easily generate admin pages of your module using Module Creator. But to understand in detail how everything works, please go through this blog.

Admin Grid

First create an ‘Adminhtml’ folder inside the Block folder of your module. And then create an Employee.php file. Here is a screen shot of entire file structure of our module Magento Admin Module File Structure
So, the Employee.php file is our grid container file, the code for this file is as follows

<?php
class Excellence_Employee_Block_Adminhtml_Employee extends Mage_Adminhtml_Block_Widget_Grid_Container
{
  public function __construct()
  {
    $this->_controller = 'adminhtml_employee';
    $this->_blockGroup = 'employee';
    $this->_headerText = Mage::helper('employee')->__('Employee Manager');
    $this->_addButtonLabel = Mage::helper('employee')->__('Add Employee');
    parent::__construct();
  }
}

Now, lets now go line by line of this file.

class Excellence_Employee_Block_Adminhtml_Employee extends Mage_Adminhtml_Block_Widget_Grid_Container

Here our class extends the Mage_Adminhtml_Block_Widget_Grid_Container class, this is very important for our Grid to work. Next we have

$this->_controller = 'adminhtml_employee';
$this->_blockGroup = 'employee';

This lines are very important, both these variables tell magento the location of our Grid.php file. If you open th eMage_Adminhtml_Block_Widget_Grid_Container class, there inside _prepareLayout() function, you will see

protected function _prepareLayout()
    {
        $this->setChild( 'grid',
            $this->getLayout()->createBlock( $this->_blockGroup.'/' . $this->_controller . '_grid',
            $this->_controller . '.grid')->setSaveParametersInSession(true) );
        return parent::_prepareLayout();
    }

So, we can see here the location of our Grid file, is located by magento based on these two variables. So in short the class name of our Grid file should be,

$this->_blockGroup.'/' . $this->_controller . '_grid'
//or 
employee/adminhtml_employee_grid

This concept, is important when you want to have multiple grids in your module
Next, we will create our Grid.php file. As mentioned above we will create our php at
Excellence/Employee/Block/Adminhtml/Employee/Grid.php

<?php

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

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

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

		$this->addColumn('name', array(
          'header'    => Mage::helper('employee')->__('Name'),
          'align'     =>'left',
          'index'     => 'name',
		  'width'     => '50px',
		));

		 
		$this->addColumn('content', array(
			'header'    => Mage::helper('employee')->__('Description'),
			'width'     => '150px',
			'index'     => 'content',
		));
		return parent::_prepareColumns();
	}
}

Now as you can see our class needs to extend Mage_Adminhtml_Block_Widget_Grid class, this is important.

  • $this->setId(‘employeeGrid’) ==> This set’s the ID of our grid i.e the html id attribute of the <div>. If you’re using multiple grids in a page then id needs to be unique
  • $this->setDefaultSort(‘id’) ==> This tells which sorting column to use in our grid. Which column should be used for default sorting
  • $this->setDefaultDir(‘ASC’) ==> The default sorting order, ascending or descending
  • $this->setSaveParametersInSession(true) ==> this basically sets your grid operations in session. Example, if we were on page2 of grid or we had searched something on grid when refreshing or coming back to the page, the grid operations will still be there. It won’t revert back to its default form.

Next we have _prepareCollection() function. This function is simple, it just returns a collection of the module we want to show in our grid. For advance collection functions read this blog post.
Next we have the _prepareColumns() function. Here we add columns to our grid.

$this->addColumn('id', array(
          'header'    => Mage::helper('employee')->__('ID'),
          'align'     =>'right',
          'width'     => '10px',
          'index'     => 'id',
		));
  • ‘id’ an unique id for column
  • ‘header’ is the name of the column
  • ‘index’ is the field from our collection. This ‘id’ column needs to be present in our collection’s models.

This is all that is needed for the showing the grid. Now, let create our controller so that we can view the grid in admin.

Admin Controller and Admin Menu

To add our module menu in admin, open the config.xml file of the module and add the following directly in the >config;< tag

<adminhtml>
		<menu>
			<employee module="employee">
				<title>Employee</title>
				<sort_order>71</sort_order>               
				<children>
					<items module="employee">
						<title>Manage Employees</title>
						<sort_order>0</sort_order>
					<action>employee/adminhtml_employee</action>
					</items>
				</children>
			</employee>
		</menu>
		<acl>
			<resources>
				<all>
					<title>Allow Everything</title>
				</all>
				<admin>
					<children>
						<Excellence_Employee>
							<title>Employee Module</title>
							<sort_order>10</sort_order>
						</Excellence_Employee>
					</children>
				</admin>
			</resources>
		</acl>
		<layout>
			<updates>
				<employee>
					<file>employee.xml</file>
				</employee>
			</updates>
		</layout>
    </adminhtml>   

I will explain the >acl< tag later, but for now focus on the >menu< tag.
The >action< is the URL of our admin controller. Suppose, if we want to add 2 menu items, we need to use the following

<children>
					<items module="employee">
						<title>Manage Employees</title>
						<sort_order>0</sort_order>
					<action>employee/adminhtml_employee</action>
					</items>
                                         <items2 module="employee">
						<title>Manage Employees</title>
						<sort_order>0</sort_order>
					<action>employee/adminhtml_employee2</action>
					</items2>
				</children>

Now, let create our controller file. Create an ‘Adminhtml’ folder in the controllers folder, as shown in the folder structure above. Next we will create our EmployeeController.php file

class Excellence_Employee_Adminhtml_EmployeeController extends Mage_Adminhtml_Controller_action
{

	public function indexAction() {
		$this->loadLayout();
                $this->renderLayout();
	}

This is same as our standard controller, only we need to extend a different class. Next, create an employee.xml layout file in our adminhtml layouts i.e design/adminhtml/default/default/layout/employee.xml. And in our config.xml we will add the entry of this new layout file, so magento knows to read this layout file as well. We have already done this above in the >adminhtml< tag. Now, the content of employee.xml is

<?xml version="1.0"?>
<layout version="0.1.0">
    <employee_adminhtml_employee_index>
        <reference name="content">
            <block type="employee/adminhtml_employee" name="employee" />
        </reference>
    </employee_adminhtml_employee_index>
</layout>

We are simply adding our Grid Container blog to the content area. For more details on layout read this blog. So now when we click the menu item from admin, it should show our grid.Admin Grid

  • Kienkun1990

    thank you very much,but you can write for me what file config in magento.
    It is very many,so I can’t understand for it.

  • http://web0.at/ d4rwin

    the post could be more helpful, if the package name and the model name would not be the same. both have the name “employee”, so it’s not totally clear, where “employee” stands for the package name and where it stands for the model name ….

    • Manish Prakash

      Ok I will try to update the blog with a different name

  • Bharanidharan K

    i have one problem,

    i create news and event modules and i set as menu links every thing is fine, but there is a loading time difference between other menus and my own module menus, other menu links are loaded very fast when compare to my own module menu.,

    can you help me pls

  • loi

    no answer? please is important

  • gagan

    Thanks alot.

  • carlosalvet

    Hi! I’m carlos from Mexico City, I’m looking for the  correct form to do multigrid modules, in this text you said is important the principal block before the grids.

    _controller = 'adminhtml_employee';$this->_blockGroup = 'employee';But i can’t find information referred to that or an example who did a module with multigrids. ¿Could you explain multigrids in a example?

  • Magento Modules

    very comprehensive information! great

    • Manish Prakash

      Thanks :)

  • http://www.facebook.com/alankar.singh1985 Alankar Singh

    Hi

    I developed a module, its working fine on localhost but not workworing on live server. its show following error exception ‘Mage_Core_Exception’ with message ‘Invalid block type: ISPG_FlatShippingRules_Block_Adminhtml_Flatshippingrules’ in /var/www/magento/app/Mage.php:594Stack trace:——-where my Module name is ‘FlatShippingRules’.
    Can anyone resolve my issue?Thanks

    • Ram

      HI ,

      Please check case of of class name.

  • Ajay

    HI Manish

    When I Click Manage Employee then it’s display blank page

    Please help me

    • http://www.facebook.com/me.cassio Cássio Fagundes

      I do not use the same name of module, but i try to adapt for you, add this lines to your config.xml inside the tag.

      Excellence_Employee_Block

  • Khanh Do

    config.xml > change module=”employee” >> module=”excellence_employee”

  • Ramki Babu

    Im getting this error.

    Fatal error: Class ‘Mage_Test_Ad_Helper_Data’ not found in C:wampwwwmagentoappMage.php on line 546

    & this is my menu coding in config.xml file

    Advertisement

    72

    Add Advertisment

    0

    ad/adminhtml_ad

    • Moaz Tariq

      change this -> to this-> as well.

  • Ramki Babu

    I m getting this error …Fatal error: Class ‘Test_Ad_Block_Data’ not found in C:wampwwwmagentoappMage.php on line 546

    Config.xml ,

    admin

    Test_Ad

    ad

    Advertisement

    71

    Add Advertisment

    0

    ad/adminhtml_ad

    Allow Everything

    Advertisement Module

    10

    ad.xml

    • Moaz Tariq

      in your helper folder create an empty helper class. In your case that will be class Test_Ad_Helper_data extends Mage_Customer_Helper_Data..hope this will work!

  • Tarun Bhalodia

    In your config.xml in add following

    Companyname_Modulename_Helper

  • Moaz6629

    i’m getting following error on admin side…
    Fatal error: Class ‘Affiliate_Request_Helper_Data’ not found in D:wampwwwmagentoappMage.php on line 546
    why is that so ?

  • Soumyajit Banerjee

    hello, I want to display a button into admin module grid when some condition match, suppose date is old at this time I want to add button into the list. But I’m unable to find this issue.