Adding a Custom Form Element to an Adminhtml Form

Posted: December 31, 2012 in Magento, Version 1.4.*, Version 1.6.*
Tags: , , , ,

Hello all,

Today i’ll show you how to add custom Form Element To an Adminhtml Form.

Create form app/code/local/CompanyName/ModuleName/Block/Form.php


class CompanyName_ModuleName_Block_Form extends Mage_Adminhtml_Block_Widget_Form
{
  protected function _prepareForm()
  {
   $form = new Varien_Data_Form(array(
     'id' => 'edit_form',
     'action' => $this->getUrl('*/*/save'),
     'method' => 'post'
   ));


   $fieldset = $form->addFieldset('fieldset', array('legend' => 'Your fieldset title')));

   //Here is what is interesting us
   //We add a new type, our type, to the fieldset
   //We call it extend_file
   $fieldset->addType('extend_file','CompanyName_ModuleName_Widget_Form_Element_ExtendFile');

   $fieldset->addField('file_element', 'extend_file', array(
     'label' => 'Label of Field',
     'name' => 'file_element',
     'required' => false,
   ));
  }
}

Code for custom element will be located here: app/code/local/CompanyName/ModuleName/Widget/Form/Element/ExtendFile.php


class CompanyName_ModuleName_Widget_Form_Element_ExtendFile extends Varien_Data_Form_Element_Abstract
{
    public function __construct($attributes=array())
    {
      parent::__construct($attributes);
      $this->setType('file');
    }

    public function getElementHtml()
    {
      if ($this->getValue()) {

        $url = Mage::getBaseUrl('media') . PATH_TO_YOUR_FILE. $this->getValue();
        $html = '<a href="'.$url.'">'.$this->getValue().'</a> ';
      }

      return $html;
    }

}

I hope above code will help to display file field value, same way we can create custom element for form.

Thanks,
Bijal Bhavsar 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s