Magento Admin Custom Form

Following on from our Custom Grid guide, we can now start adding a Magento admin custom form, where we’ll be able to add, edit and remove data.

We saw previously that Magento grids extend the Mage_Adminhtml_Block_Widget_Grid_Container and Mage_Adminhtml_Block_Widget_Grid classes.

Magento forms extend the Mage_Adminhtml_Block_Widget_Form_Container and Mage_Adminhtml_Block_Widget_Form classes.

So we’re looking to add two further files; an Edit.php and a Form.php file.

Let’s start with the Edit.php file. This should belong in the same directory as the Stores.php file. The Edit.php file will be the file that extends the Mage_Adminhtml_Block_Widget_Form_Container.

<?php
class Custom_Storeinfo_Block_Adminhtml_Stores_Edit extends Mage_Adminhtml_Block_Widget_Form_Container {

We now need to add a couple of methods to the class.

public function __construct()
{
    $this->_blockGroup = 'storeinfo';
    $this->_controller = 'adminhtml_stores';

    parent::__construct();

    $this->_updateButton('save', 'label', $this->__('Save Store'));
    $this->_updateButton('delete', 'label', $this->__('Delete Store'));
}

/**
 * Get Header text
 *
 * @return string
 */
public function getHeaderText()
{
    if (Mage::registry('storeinfo')->getId()) {
        return $this->__('Edit Store');
    }
    else {
        return $this->__('New Store');
    }
}

The __construct() method is similar to what we saw in the __construct() method of the grid container class. The $this->_blockGroup value comes from the alias of our block declaration in config.xml.

The getHeaderText() method sets the header text to either be Edit Store or New Store depending on if we’ve clicked to add or edit a new store. The value of the record that has been clicked on is stored in Magento’s registry (which will become apparent later on in the article).

Now we need to add the Form.php which extends the Mage_Adminhtml_Block_Widget_Form class. The Form.php should be added within an Edit directory, which can be found on the same directory level as the Edit.php file.

<?php
class Custom_Storeinfo_Block_Adminhtml_Stores_Edit_Form extends Mage_Adminhtml_Block_Widget_Form {
    public function __construct()
    {
        parent::__construct();

        $this->setId('storeinfo_form');
        $this->setTitle($this->__('Store Information'));
    }

    /**
     * Setup form fields for inserts/updates
     *
     * return Mage_Adminhtml_Block_Widget_Form
     */
    protected function _prepareForm()
    {
        $model = Mage::registry('storeinfo');

        $form = new Varien_Data_Form(array(
            'id'        => 'edit_form',
            'action'    => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
            'method'    => 'post'
        ));

        $fieldset = $form->addFieldset('base_fieldset', array(
            'legend'    => Mage::helper('storeinfo')->__('Store Information'),
            'class'     => 'fieldset-wide',
        ));

        if ($model->getId()) {
            $fieldset->addField('id', 'hidden', array(
                'name' => 'id',
            ));
        }

        $fieldset->addField('name', 'text', array(
            'name'      => 'name',
            'label'     => Mage::helper('storeinfo')->__('Name'),
            'title'     => Mage::helper('storeinfo')->__('Name'),
            'required'  => true,
        ));

        $fieldset->addField('description', 'text', array(
            'name'      => 'description',
            'label'     => Mage::helper('storeinfo')->__('Description'),
            'title'     => Mage::helper('storeinfo')->__('Description'),
            'required'  => true,
        ));

        $form->setValues($model->getData());
        $form->setUseContainer(true);
        $this->setForm($form);

        return parent::_prepareForm();
    }
}

Now that we have added the blocks, we need to add a few action methods to our controller.

Let’s start with the newAction(), which will be the action when the Add Store button is clicked. We will forward this action to the editAction() method.

public function editAction()
{
    // Get id if available
    $id  = $this->getRequest()->getParam('id');
    $model = Mage::getModel('storeinfo/store');

    if ($id) {
        // Load record
        $model->load($id);

        // Check if record is loaded
        if (!$model->getId()) {
            Mage::getSingleton('adminhtml/session')->addError($this->__('This store no longer exists.'));
            $this->_redirect('*/*/');

            return;
        }
    }

    Mage::register('storeinfo', $model);

    $this->loadLayout();
    $this->_addContent($this->getLayout()->createBlock('storeinfo/adminhtml_stores_edit'));
    $this->renderLayout();
}

So there a few things to note from above.

  • We perform an initial check to ensure that the ID exists
  • We register the data of our store using the register() method of the Mage.php class
  • We then call our edit block, which is the Edit.php we created.

Now when you click on a record, or go to add a new one, we have our very basic form! We still have to set up save and delete actions, so let’s set up these now.

public function saveAction()
{
    if ( $this->getRequest()->getPost() ) {
        $postData = $this->getRequest()->getPost();
        $storeInfoModel = Mage::getModel('storeinfo/store');

        $store = $storeInfoModel->load($this->getRequest()->getParam('id'));
        $store->setName($postData['name'])
              ->setDescription($postData['description'])
              ->save();

        Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Store was successfully saved'));
        Mage::getSingleton('adminhtml/session')->setStoreData(false);

        $this->_redirect('*/*/');
        return;
    }
    $this->_redirect('*/*/');
}
public function deleteAction()
{
    if( $this->getRequest()->getParam('id') > 0 ) {
        try {
            $storeModel = Mage::getModel('storeinfo/store');

            $storeModel->setId($this->getRequest()->getParam('id'))
                ->delete();

            Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Store was successfully deleted'));
            $this->_redirect('*/*/');
        } catch (Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
        }
    }
    $this->_redirect('*/*/');
}

Note: This article is based on Magento Community/Open Source version 1.9.