Posts Tagged ‘widget’

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