Monday , December 11 2017
Home >> All tutorial >> Magento Developers’ Guide – Part 7: The Magento admin grid

Magento Developers’ Guide – Part 7: The Magento admin grid

In the Magento administration, when you want to list your products, you see a GridView (a kind of table with which can be sorted, edit an article, delete etc …) and you’ll say that it could be nice to use the same in our module. In this tutorial we’ll see how to insert a GridView in the administration part of our Magento plugin.

Magento Grid is constructed from a set of files that you will find in the file Block/Adminhtml from your module.

1 – The Grid Container

Create a folder: \app\code\local\Pfay\Test\Block\Adminhtml\ and put in a file Grid.php. This is the file which (as its name suggests) will contain your Grid. It contains:

  1. <?php
  2. class Pfay_Test_Block_Adminhtml_Grid extends Mage_Adminhtml_Block_Widget_Grid_Container
  3. {
  4.     public function __construct()
  5.     {
  6.      //where is the controller
  7.      $this->_controller = ‘adminhtml_test’;
  8.      $this->_blockGroup = ‘test’;
  9.      //text in the admin header
  10.      $this->_headerText = ‘Adressbook management’;
  11.      //value of the add button
  12.      $this->_addButtonLabel = ‘Add a contact’;
  13.      parent::__construct();
  14.      }
  15. }

2 – The Grid

You indicate that the controller’s grid will be in the test folder, create the folder then create a folder:\app\code\local\Pfay\Test\Block\Adminhtml\Test\ and create a file Grid.php in it containing :

  1. <?php
  2. class Pfay_Test_Block_Adminhtml_Test_Grid extends Mage_Adminhtml_Block_Widget_Grid
  3. {
  4.    public function __construct()
  5.    {
  6.        parent::__construct();
  7.        $this->setId(‘contactGrid’);
  8.        $this->setDefaultSort(‘id_pfay_test’);
  9.        $this->setDefaultDir(‘DESC’);
  10.        $this->setSaveParametersInSession(true);
  11.    }
  12.    protected function _prepareCollection()
  13.    {
  14.       $collection = Mage::getModel(‘test/test’)->getCollection();
  15.       $this->setCollection($collection);
  16.       return parent::_prepareCollection();
  17.     }
  18.    protected function _prepareColumns()
  19.    {
  20.        $this->addColumn(‘id_pfay_test’,
  21.              array(
  22.                     ‘header’ => ‘ID’,
  23.                     ‘align’ =>‘right’,
  24.                     ‘width’ => ’50px’,
  25.                     ‘index’ => ‘id_pfay_test’,
  26.                ));
  27.        $this->addColumn(‘nom’,
  28.                array(
  29.                     ‘header’ => ‘nom’,
  30.                     ‘align’ =>‘left’,
  31.                     ‘index’ => ‘nom’,
  32.               ));
  33.        $this->addColumn(‘prenom’, array(
  34.                     ‘header’ => ‘prenom’,
  35.                     ‘align’ =>‘left’,
  36.                     ‘index’ => ‘prenom’,
  37.              ));
  38.         $this->addColumn(‘telephone’, array(
  39.                      ‘header’ => ‘telephone’,
  40.                      ‘align’ =>‘left’,
  41.                      ‘index’ => ‘telephone’,
  42.           ));
  43.          return parent::_prepareColumns();
  44.     }
  45.     public function getRowUrl($row)
  46.     {
  47.          return $this->getUrl(‘*/*/edit’, array(‘id’ => $row->getId()));
  48.     }
  49. }
We configure our magento Grid , stating the collection use to interact with the database in prepareCollection() (here we will use the collection of model ‘test/test’ created in the previous tutorials). Then with prepareColumns() he says which columns of our table with a display method addColumn(). I don’t explain the code more than that, it seems to me pretty obvious that if you want to add a column, just add an entry like this:
  1. $this->addColumn(‘telephone’,
  2.  array(
  3.      ‘header’ => ‘telephone’,
  4.      ‘align’ =>‘left’,
  5.      ‘index’ => ‘telephone’,
  6.  ));

Here, our Grid is now configured. Now, when we will click on one of the columns, we have to arrive on a form to edit our contact.

3 – The Form Container

So create a file edit.php in the same directory:\app\code\local\Pfay\Test\Block\Adminhtml\Test\
This file edit.php will contain the following code:

  1. <?php
  2. class Pfay_Test_Block_Adminhtml_Test_Edit extends
  3.                     Mage_Adminhtml_Block_Widget_Form_Container{
  4.    public function __construct()
  5.    {
  6.         parent::__construct();
  7.         $this->_objectId = ‘id’;
  8.         //vwe assign the same blockGroup as the Grid Container
  9.         $this->_blockGroup = ‘test’;
  10.         //and the same controller
  11.         $this->_controller = ‘adminhtml_test’;
  12.         //define the label for the save and delete button
  13.         $this->_updateButton(‘save’, ‘label’,‘save reference’);
  14.         $this->_updateButton(‘delete’, ‘label’, ‘delete reference’);
  15.     }
  16.        /* Here, we’re looking if we have transmitted a form object,
  17.           to update the good text in the header of the page (edit or add) */
  18.     public function getHeaderText()
  19.     {
  20.         if( Mage::registry(‘test_data’)>>Mage::registry(‘test_data’)->getId())
  21.          {
  22.               return ‘Editer la reference ‘.$this->htmlEscape(
  23.               Mage::registry(‘test_data’)->getTitle()).‘<br />’;
  24.          }
  25.          else
  26.          {
  27.              return ‘Add a contact’;
  28.          }
  29.     }
  30. }

I’ve commented the code, this file is a Form Container (see extends) That’s a structure that will allow you to receive application forms. Now we have to do the form itself.

4 – Create Form

Now create the folder:\app\code\local\Pfay\Test\Block\Adminhtml\Test\Edit\in the file and form.php

This file will contain the following code:

  1. class Pfay_Test_Block_Adminhtml_Test_Edit_Form extends
  2.                           Mage_Adminhtml_Block_Widget_Form
  3. {
  4.     protected function _prepareForm()
  5.     {
  6.          $form = new Varien_Data_Form(
  7.                 array(
  8.                   ‘id’ => ‘edit_form’,
  9.                   ‘action’ => $this->getUrl(‘*/*/save’, array(‘id’ => $this->getRequest()->getParam(‘id’))
  10.                      ),
  11.                  ‘method’ => ‘post’,
  12.                  )
  13.               );
  14.       $form->setUseContainer(true);
  15.       $this->setForm($form);
  16.       return parent::_prepareForm();
  17.    }
  18. }

Here we create an object of type Varien_Data_Form that’s the « standard » magento form, we set the action attribute of the form with the function getUrl() and we defines the method of sending information (by post).
And that’s all, we have defined our information form. Now we will create the lines of our form. In our directory\app\code\local\Pfay\Test\Block\Adminhtml\Test\Edit\, create a file Tabs.php which is actually a kind of « tabs container »)

This file will contain the following code:

  1. <?php
  2.   class Pfay_Test_Block_Adminhtml_Test_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
  3.   {
  4.      public function __construct()
  5.      {
  6.           parent::__construct();
  7.           $this->setId(‘test_tabs’);
  8.           $this->setDestElementId(‘edit_form’);
  9.           $this->setTitle(‘Information sur le contact’);
  10.       }
  11.       protected function _beforeToHtml()
  12.       {
  13.           $this->addTab(‘form_section’, array(
  14.                    ‘label’ => ‘Contact Information’,
  15.                    ‘title’ => ‘Contact Information’,
  16.                    ‘content’ => $this->getLayout()
  17.      ->createBlock(‘test/adminhtml_test_edit_tab_form’)
  18.      ->toHtml()
  19.          ));
  20.          return parent::_beforeToHtml();
  21.     }
  22. }
That entries will be created through block in the plugin Test, which will adminhtml_test_edit_tab_form, then create the folder:\app\code\local\Pfay\Test\Block\Adminhtml\Test\Edit\Tab and create the file in form.php .
  1. <?php
  2. class Pfay_Test_Block_Adminhtml_Test_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
  3. {
  4.    protected function _prepareForm()
  5.    {
  6.        $form = new Varien_Data_Form();
  7.        $this->setForm($form);
  8.        $fieldset = $form->addFieldset(‘test_form’,
  9.                                        array(‘legend’=>‘ref information’));
  10.         $fieldset->addField(‘nom’, ‘text’,
  11.                        array(
  12.                           ‘label’ => ‘Nom’,
  13.                           ‘class’ => ‘required-entry’,
  14.                           ‘required’ => true,
  15.                            ‘name’ => ‘nom’,
  16.                     ));
  17.         $fieldset->addField(‘prenom’, ‘text’,
  18.                          array(
  19.                           ‘label’ => ‘Prenom’,
  20.                           ‘class’ => ‘required-entry’,
  21.                           ‘required’ => true,
  22.                           ‘name’ => ‘prenom’,
  23.                       ));
  24.           $fieldset->addField(‘telephone’, ‘text’,
  25.                     array(
  26.                         ‘label’ => ‘telephone’,
  27.                         ‘class’ => ‘required-entry’,
  28.                         ‘required’ => true,
  29.                         ‘name’ => ‘telephone’,
  30.                  ));
  31.  if ( Mage::registry(‘test_data’) )
  32.  {
  33.     $form->setValues(Mage::registry(‘test_data’)->getData());
  34.   }
  35.   return parent::_prepareForm();
  36.  }
  37. }

5 – Insert our block in Layout

Then in the layout.xml your theme of directors, change your block by:

  1. <block type=“test/adminhtml_grid” name=“test” />

That’s all, your grid works very well ! (no ? huhu…try again ??). Congratulations !!…Oh it not working :’(….it does not change? this is normal, you must implement the save method in your magento controller !

6 – Implement the functions in the controller

So go in your \app\code\local\Pfay\Test\controllers\Adminhtml\IndexController.php and edit it like this:

  1. <?php
  2. class Pfay_Test_Adminhtml_IndexController extends Mage_Adminhtml_Controller_Action
  3. {
  4.     protected function _initAction()
  5.     {
  6.         $this->loadLayout()->_setActiveMenu(‘test/set_time’)
  7.                 ->_addBreadcrumb(‘test Manager’,‘test Manager’);
  8.        return $this;
  9.      }
  10.       public function indexAction()
  11.       {
  12.          $this->_initAction();
  13.          $this->renderLayout();
  14.       }
  15.       public function editAction()
  16.       {
  17.            $testId = $this->getRequest()->getParam(‘id’);
  18.            $testModel = Mage::getModel(‘test/test’)->load($testId);
  19.            if ($testModel->getId() || $testId == 0)
  20.            {
  21.              Mage::register(‘test_data’, $testModel);
  22.              $this->loadLayout();
  23.              $this->_setActiveMenu(‘test/set_time’);
  24.              $this->_addBreadcrumb(‘test Manager’, ‘test Manager’);
  25.              $this->_addBreadcrumb(‘Test Description’, ‘Test Description’);
  26.              $this->getLayout()->getBlock(‘head’)
  27.                   ->setCanLoadExtJs(true);
  28.              $this->_addContent($this->getLayout()
  29.                   ->createBlock(‘test/adminhtml_test_edit’))
  30.                   ->_addLeft($this->getLayout()
  31.                   ->createBlock(‘test/adminhtml_test_edit_tabs’)
  32.               );
  33.              $this->renderLayout();
  34.            }
  35.            else
  36.            {
  37.                  Mage::getSingleton(‘adminhtml/session’)
  38.                        ->addError(‘Test does not exist’);
  39.                  $this->_redirect(‘*/*/’);
  40.             }
  41.        }
  42.        public function newAction()
  43.        {
  44.           $this->_forward(‘edit’);
  45.        }
  46.        public function saveAction()
  47.        {
  48.          if ($this->getRequest()->getPost())
  49.          {
  50.            try {
  51.                  $postData = $this->getRequest()->getPost();
  52.                  $testModel = Mage::getModel(‘test/test’);
  53.                if( $this->getRequest()->getParam(‘id’) <= 0 )
  54.                   $testModel->setCreatedTime(
  55.                      Mage::getSingleton(‘core/date’)
  56.                             ->gmtDate()
  57.                     );
  58.                   $testModel
  59.                     ->addData($postData)
  60.                     ->setUpdateTime(
  61.                              Mage::getSingleton(‘core/date’)
  62.                              ->gmtDate())
  63.                     ->setId($this->getRequest()->getParam(‘id’))
  64.                     ->save();
  65.                  Mage::getSingleton(‘adminhtml/session’)
  66.                                ->addSuccess(‘successfully saved’);
  67.                  Mage::getSingleton(‘adminhtml/session’)
  68.                                 ->settestData(false);
  69.                  $this->_redirect(‘*/*/’);
  70.                 return;
  71.           } catch (Exception $e){
  72.                 Mage::getSingleton(‘adminhtml/session’)
  73.                                   ->addError($e->getMessage());
  74.                 Mage::getSingleton(‘adminhtml/session’)
  75.                  ->settestData($this->getRequest()
  76.                                     ->getPost()
  77.                 );
  78.                 $this->_redirect(‘*/*/edit’,
  79.                             array(‘id’ => $this->getRequest()
  80.                                                 ->getParam(‘id’)));
  81.                 return;
  82.                 }
  83.               }
  84.               $this->_redirect(‘*/*/’);
  85.             }
  86.           public function deleteAction()
  87.           {
  88.               if($this->getRequest()->getParam(‘id’) > 0)
  89.               {
  90.                 try
  91.                 {
  92.                     $testModel = Mage::getModel(‘test/test’);
  93.                     $testModel->setId($this->getRequest()
  94.                                         ->getParam(‘id’))
  95.                               ->delete();
  96.                     Mage::getSingleton(‘adminhtml/session’)
  97.                                ->addSuccess(‘successfully deleted’);
  98.                     $this->_redirect(‘*/*/’);
  99.                  }
  100.                  catch (Exception $e)
  101.                   {
  102.                            Mage::getSingleton(‘adminhtml/session’)
  103.                                 ->addError($e->getMessage());
  104.                            $this->_redirect(‘*/*/edit’, array(‘id’ => $this->getRequest()->getParam(‘id’)));
  105.                   }
  106.              }
  107.             $this->_redirect(‘*/*/’);
  108.        }
  109. }
  110. ?>
This is the end of this tutorial today. Read more about Magento Grid here.

We also contribute great content of Magento Download for FREE (all versions)

DON'T MISS THE CHANCE!

magento download

About Champ

Leave a Reply

Your email address will not be published. Required fields are marked *

Heap | Mobile and Web Analytics