Module Development Series – Magento Admin Module – Part3

Banners
In this blog post, we will see how to create basic admin forms.

In the previous blog post we had seen details of admin grid, in this post we will see details of how to create forms in admin.
Forms in magento are divided in two 4 basic parts
1. FORM Container
2. FORM tag
3. FORM Tabs
4. Actual Form Fields
Before seeing what these are in detail, let see first the code to put in your admin controller to display a form

Controller Form Display

You need to put in this code in which ever action you want to display the form

public function newAction(){
$this->loadLayout();
$this->_addContent($this->getLayout()->createBlock('form/adminhtml_form_edit'))
				->_addLeft($this->getLayout()->createBlock('form/adminhtml_form_edit_tabs'));
$this->renderLayout();
}

As you can see here we are adding two blocks to content and left. The main form container gets added to the content and the tabs block gets added to left.

FORM Container

The form container is, as the name suggest the main div tag inside which all the form elements/html is placed. To create a form container you need to create a php file inside your Block/Adminhtml folder which extends Mage_Adminhtml_Block_Widget_Form_Container class.
Lets name our container file as Form.php

<?php
class Excellence_Form_Block_Adminhtml_Form_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
    public function __construct()
    {
        parent::__construct();
                 
        $this->_objectId = 'id';
        $this->_blockGroup = 'form';
        $this->_controller = 'adminhtml_form';
        
        $this->_updateButton('save', 'label', Mage::helper('form')->__('Save'));
        $this->_updateButton('delete', 'label', Mage::helper('form')->__('Delete'));
		
        $this->_addButton('saveandcontinue', array(
            'label'     => Mage::helper('adminhtml')->__('Save And Continue Edit'),
            'onclick'   => 'saveAndContinueEdit()',
            'class'     => 'save',
        ), -100);
    }

    public function getHeaderText()
    {
        return Mage::helper('form')->__('My Form Container');
    }
}

Attached is a screenshot of the form container Admin Form Container
Important things in the class are

  • getHeaderText(): This function return’s the Text to display as the form header. You can see the form header in the screenshot attached Admin Form Container.
  • $this->_objectId: This variable is used in the form URL’s. This variable has the forms entity primary key, e.g the delete button URL would be module/controller/action/$this->_objectid/3
  • $this->_blockGroup = ‘form'; and $this->_controller = ‘adminhtml_form'; There two variables are very important, these variables are used to find FORM tabs php file. i.e the path of the form tabs php should be {$this->_blockGroup . ‘/’ . $this->_controller . ‘_’ . $this->_mode . ‘_form’}. The value of $this->_mode by default is ‘edit’. So the path of the php file which contains the form tag in our case would be ‘form/adminhtml_form_edit_form’.
  • $this->_updateButton() and $this->_addButton() are used to update/add buttons to the form container. These buttons are visible in the screenshot Admin Form Container
Form tag

This php file contains the actual <form> tag. The code in this file is

<?php
class Excellence_Form_Block_Adminhtml_Form_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
  protected function _prepareForm()
  {
      $form = new Varien_Data_Form(array(
                                      'id' => 'edit_form',
                                      'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
                                      'method' => 'post',
        							  'enctype' => 'multipart/form-data'
                                   )
      );

      $form->setUseContainer(true);
      $this->setForm($form);
      return parent::_prepareForm();
  }
}

As mentioned earlier, the class path of this file is automatically decided based on the variables {$this->_blockGroup . ‘/’ . $this->_controller . ‘_’ . $this->_mode . ‘_form’} defined in the form container class. As you can see the code, it is pretty simple we set the form id, action, method and enctype of the form.

Form Tabs

This is used to add tabs to our form. See attached screenshot to know what this means

Magento Admin Form Tabs

Magento Admin Form Tabs


The class of this php would be Excellence_Form_Block_Adminhtml_Form_Edit_Tabs, this is the block class we had used in our controller file.

<?php
class Excellence_Form_Block_Adminhtml_Form_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{

  public function __construct()
  {
      parent::__construct();
      $this->setId('form_tabs');
      $this->setDestElementId('edit_form'); // this should be same as the form id define above
      $this->setTitle(Mage::helper('form')->__('Product Information'));
  }

  protected function _beforeToHtml()
  {
      $this->addTab('form_section', array(
          'label'     => Mage::helper('form')->__('Item Information'),
          'title'     => Mage::helper('form')->__('Item Information'),
          'content'   => $this->getLayout()->createBlock('form/adminhtml_form_edit_tab_form')->toHtml(),
      ));
     
      return parent::_beforeToHtml();
  }
}

Here the $this->addTab function is used to add as many tabs as you want in your form. Right now we have only one tab with title ‘Item Information’ and the content is coming from the block class ‘form/adminhtml_form_edit_tab_form’.

Actual Form Fields

Now we need to create the actual form fields, the code is

<?php
class Excellence_Form_Block_Adminhtml_Form_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
	protected function _prepareForm()
	{
		$form = new Varien_Data_Form();
		$this->setForm($form);
		$fieldset = $form->addFieldset('form_form',               array('legend'=>Mage::helper('form')->__('Item information')));
		 
		$fieldset->addField('title', 'text', array(
          'label'     => Mage::helper('form')->__('Title'),
          'class'     => 'required-entry',
          'required'  => true,
          'name'      => 'title',
		));
		 
		return parent::_prepareForm();
	}
}

Here we have simply added one textfield to the form.

Saving Form

The form get saved to the to the action which we have defined in the class Excellence_Form_Block_Adminhtml_Form_Edit_Form, in our case the action is
$this->getUrl(‘*/*/save’, array(‘id’ => $this->getRequest()->getParam(‘id’))
So in our adminhtml controller, we need to create saveAction() where we can access the form fields using post data and do further processing as we like.

public function saveAction() {
		if ($data = $this->getRequest()->getPost()) {
                }
}
In this blog post we have seen only basic admin form operations. In the next post we will see advanced functions we can use in admin forms.
  • Pingback: Manage Admin Module : Form Field « infirock

  • helgvor_stoll

    Hi,

    First i must thank you for your excellent tutorial. It helped me a lot.
    But I would like to know how you can add 2 fieldsets on the same line (one in a left box and the other one in a right box, like on the order view form).

    In fact, when doing:

          $form = new Varien_Data_Form();      $this->setForm($form);       $fieldset = $form->addFieldset(‘web_form’, array(‘legend’=>Mage::helper(‘web’)->__(‘Other Form’)));
                …..
          $fieldset2 = $form->addFieldset(‘web_formn’, array(‘legend’=>Mage::helper(‘web’)->__(‘Second Form’)));

    The second fieldset is above the first one.

    Have you an idea?

    Thanks in advance,

    Helgvor STOLL

  • Nathan

    Would it be possible for you to put the directorypath/file location in a comment in the code samples?

  • Will

    Hello everybody,

    This post is very helpfull, but I have a question.

    When I am editing a information the form isn’t populated. How can I do this?

    Thank you ;)

  • Balu Antony

    i want to create one new dropdown menu(orderposting) inside sales module… i already added orderposting module inside sales module but im unable to create table inside orderposting module……

  • Marcelo Jacobus

    I learnt a lot from it. However I feel like the module name being ‘Form’ comfused me a bit.

  • Marko

    Nice tutorial, i learned a lot.
    But how can we create a form without tabs? Is possible to create a view page, like the one in sales->invoice->view(action) instead of a edit page?