Magento - Custom form element: text button

Create a custom form element for text buttons with a specific action.
Magento - Custom form element: text button Image

Create the block class (for example, Mypackage_Mymodule_Block_Form_Element_Textbutton):

class Mypackage_Mymodule_Block_Form_Element_Textbutton extends Mage_Adminhtml_Block_Template
{

public function getElementHtml()
{
$data = $this->getData();
$url = Mage::helper("adminhtml")->getUrl($data['custom_url'],$data['params']);
$html =
'<div style="margin:6px 0px;">'.$data['prefix_text'].'</div>'.
Mage::app()->getLayout()->createBlock('adminhtml/widget_button')
->setType('button')
->setLabel($data['button_text'])
->setOnClick("window.open('$url','_self')")
->toHtml().'<input type="hidden" id="'.$data['name'].'" name="'.$data['name'].'" value="'.$data['field_value'].'"/>';
if($this->getUpdated())
{
$html.='<script type="text/javascript">window.onload=function(){ $(\''.$data['tab_id'].'\').className+=" changed"; } </script>';
}
return $html;
}

}

Then you just need to implement the block, for example in your admin form:

$blockDataArray = array

(
'name' => 'button_name',
'field_value' => $buttonValue,
'updated' => $formUpdated,
'params' => array('othervalue'=>$otherValue),
'custom_url' => 'adminhtml/yourcontroller/youraction/',
'prefix_text' => $preText,
'button_text' => $buttonLabel,
'tab_id' => 'yourmodule_tab_id'
);


$itemText = $this->getLayout()

->createBlock('yourmodule/form_element_textbutton')
->setData($blockDataArray)
->getElementHtml();


$fieldset->addField('field_id', 'note', array(
'label' => Mage::helper('adminhtml')->__('Field Label'),
'name' => 'field_id',
'required' => true,
'text' => $itemText
));

And that's all.

Leave your comment

* Required Fields