Adding a Custom Form Element to an Adminhtml Form

后端 未结 3 1556
[愿得一人]
[愿得一人] 2021-02-02 16:00

Is there a way to add a custom form element to a Magento Adminhtml form without placing the custom element in the lib/Varian folder?

I\'ve tracked down the

3条回答
  •  面向向阳花
    2021-02-02 16:51

    This is an old post but it still can be usefull for someone :

    yes you can.

    The code below is located in : app/code/local/MyCompany/MyModule/Block/MyForm.php

    class MyCompany_MyModule_Block_MyForm 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('my_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 extended_label
            $fieldset->addType('extended_label','MyCompany_MyModule_Lib_Varien_Data_Form_Element_ExtendedLabel');
    
            $fieldset->addField('mycustom_element', 'extended_label', array(
                'label'         => 'My Custom Element Label',
                'name'          => 'mycustom_element',
                'required'      => false,
                'value'     => $this->getLastEventLabel($lastEvent),
                'bold'      =>  true,
                'label_style'   =>  'font-weight: bold;color:red;',
            ));
        }
    }
    

    Here is the code of your custom element, which is located in app/code/local/MyCompany/MyModule/Lib/Varien/Data/Form/Element/ExtendedLabel.php :

    class MyCompany_MyModule_Lib_Varien_Data_Form_Element_ExtendedLabel extends Varien_Data_Form_Element_Abstract
    {
        public function __construct($attributes=array())
        {
            parent::__construct($attributes);
            $this->setType('label');
        }
    
        public function getElementHtml()
        {
            $html = $this->getBold() ? '' : '';
            $html.= $this->getEscapedValue();
            $html.= $this->getBold() ? '' : '';
            $html.= $this->getAfterElementHtml();
            return $html;
        }
    
        public function getLabelHtml($idSuffix = ''){
            if (!is_null($this->getLabel())) {
                $html = ''."\n";
            }
            else {
                $html = '';
            }
            return $html;
        }
    }
    

提交回复
热议问题