Tuesday, April 3, 2012

Magento - How to add new field type into Varien_Data_Form

Happens so that in the admin panel when we create new forms then it is necessary to add some element to the form Varien_Data_Form. Following example will shows how it can be done.

<?php
class My_Module_Block_Adminhtml_Product_Edit_Tab_Types extends Mage_Adminhtml_Block_Widget_Form
{
    //...

    /**
     * Prepare form
     *
     * @return Mage_Adminhtml_Block_Widget_Form
     */
    public function _prepareForm()
    {
        $form = new Varien_Data_Form();
        $this->setForm($form);
        $fieldset = $form->addFieldset('base_fieldset', array());

        $fieldset->addType('my_type',
            Mage::getConfig()->getBlockClassName('myModule/adminhtml_renderer_myType'));

        $fieldset->addField('my_type', 'label', array(
            'name'      => 'name_my_type',
            'label'     => $this->__('My Type'),
            'value'     => 'default value',
            'value_class'   => 'my-type-css-class',
        ));
        parent::_prepareForm();
        return $this;
    }

    //...
}

Next step we need to create necessary render model.


<?php
class My_Module_Block_Adminhtml_Renderer_MyType extends Varien_Data_Form_Element_Abstract
{
    /**
     * Get Html output.
     *
     * @return string
     */
    public function getElementHtml()
    {
        //do something for make HTML output
        $toHtml = "<div>My Type</div>"
        return $toHtml;
    }
}

That's all.
Post a Comment