Lesson 10: Advanced Magento form in Backend

Advanced magento form in backend
Hello guys, in the last lesson, you have learned about form and basic ingredients of a Magento form in backend in our Magento Tutorial. Today, you will learn about it at a higher level. Welcome to lesson 10: Advanced Magento form in Backend.
The lesson “Advanced Magento form in Backend” has 3 main parts:
1. Normal html tabs and tabs using AJAX.
2. Renderer field in form
a. Magento form fields
b. Custom form field
3. Custom purpose button

After learning this lesson, you are expected to understand and use advanced magento form in backend more flexibly.

[yellowbox] Exclusive bonus: Rocket your sales by right segment, right target! Magento modules and Magento 2 modules are powerful extensions for your web-store [/yellowbox]

Normal HTML tabs and tabs using AJAX

Below is a tab in Magento:

Advanced Magento form in backend-magento tabs

a. Add normal html tabs

In order to add  new html tabs, you should notice the file Tabs.php. You can easily find this file through this link app/code/local/{your_namespace}/{your_module}/block/adminhtml/{section}/edit/
After opening the file Tabs.php, you can see:

class Magestore_Lesson10_Block_Adminhtml_Lesson10_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs
{
public function __construct()
{
parent::__construct();
$this->setId('lesson10_tabs');
$this->setDestElementId('edit_form');
$this->setTitle(Mage::helper('lesson10')->__('Item Information'));
}
/**
* prepare before render block to html
*
* @return Magestore_Lesson10_Block_Adminhtml_Lesson10_Edit_Tabs
*/
protected function _beforeToHtml()
{
$this->addTab('form_section', array(
'label' => Mage::helper('lesson10')->__('Normal HTML Tab'),
'title' => Mage::helper('lesson10')->__('Normal HTML Tab'),
'content' => $this->getLayout()
->createBlock('lesson10/adminhtml_lesson10_edit_tab_form')
->toHtml(),
));
}
}

You should note following points:
– The 1st is the function addTab() which will help you add  normal html tabs. It includes 2 parameters:

  • tabId : Unique Id for tab. Here, the Id of tab is “form_section”
  • tab: array containing the declaration about tab’s attributes. Besides array, you can also use an object or a string.

I advise you to go to the parent class Mage_Adminhtml_Block_Widget_Tabs to know more about this method.
– The 2nd is attributes declared in the array

  • ‘Label’: display name of tab
  • ‘Title’: Title of tab
  • ‘Content’: As you can see, it defines the content in a tab. Tab’s content is a HTM. You can totally change the link in the functioncreateBlock() to change the tab’s content.

From now on, you can add as many normal html tabs as you want in a similar way.

b. Add AJAX based tabs

In the previous part, you have learned how to add  normal html tabs and in this part, you will learn how to add an Ajax-based tabs.
The difference between an Ajax-based tab and a normal HTML tab is that Ajax-based tab uses Ajax to load content of tab. The tab’s content is loaded only when we click on the tab. After you click on an Ajax tab, the waiting icon will appear while Ajax is loading the content. In reality, Ajax-based tab is often used when you want to add a grid to tab. Below is one example:
Advanced magento form in Backend.

 

 

 

Going on with the file Tabs.php, the following code will help me add an Ajax tab to form:

$this->addTab('ajax_base_tab', array(
'label' => Mage::helper('lesson10')->__('Tab using AJAX'),
'url' => $this->getUrl('*/*/ajaxTab', array('_current' => true)),
'class' => 'ajax',
));
return parent::_beforeToHtml();

Here we have named the class “ajax” and add an URL to ajax to load. This URL will call the function ajaxTabAction() in the admin controller. This function will give out the tab’s content.

public function ajaxTabAction(){
$this->loadLayout();
$this->getResponse()->setBody(
$this->getLayout()
->createBlock('lesson10/adminhtml_lesson10_edit_tab_ajaxtab');
->toHtml()
);
}

Please remember that basically, tab’s content is a HTML code. Based on the objective of using tab, we should flexibly use the normal or ajax tab. Result:
 Advanced magento form in Backend

 

 

 

[yellowbox] Exclusive bonus: You need tools to make your Magento site stronger than ever? We have ones. Check out Magento extensions that can help you boost your sales and increase customers’ engagement. [/yellowbox]

2. Renderer field in form

a. Magento form fields

Magento has many different types of field available by default. So let’s see the syntax of using each of these fields. All the different types of Magento form fields available are located in the folder lib\Varien\Data\Form\Element. Here are some types that I often use.
i. Text
This is how to add a text field to an admin form, with a list of all the options.

 $fieldset->addField(name, 'text', array(
'label' => Mage::helper('form')->__('Name'),
'class' => 'required-entry',
'required' => true,
'name' => 'name',
'onclick' => "alert('on click');",
'onchange' => "alert('on change');",
'style' => "border:10px",
'disabled' => false,
'readonly' => true,
'after_element_html' => 'Textfield',
));

I will explain some properties in the array so that you can easily understand other elements below.

  • Label: The label of the field
  • Class: Class of the element which was defined in css
  • Required: Whether the field is required or not.
  • Onclick: Response when you click on the element
  • Onchange: Response when you change the value of the element
  • Readonly: Whether the field can be edited or not
  • Disabled: Whether the field is disabled or not
  • After_element_html: What is right after the element. It may be some texts or another element.

ii. Text area

$fieldset->addField('textarea', 'textarea', array(
'label' => Mage::helper('form')->__('TextArea'),
'class' => 'required-entry',
'required' => true,
'name' => 'title',
'onclick' => "",
'onchange' => "",
'disabled' => false,
'readonly' => false,
'after_element_html' => 'Text area',
));

iii. Note

$fieldset->addField('note', 'note', array(
'text' => Mage::helper('form')->__('Text Text'),
));

iv. Date

$fieldset->addField('date', 'date', array(
'label' => Mage::helper('form')->__('Date'),
'after_element_html' => 'Date',
'image' => $this->getSkinUrl('images/grid-cal.gif'),
'format' => Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM)
));

There are 2 properties that you need to know:

  • Image: The image that is shown besides the field
  • Format: The date format type. You can change it to FORMAT_TYPE_FULL, FORMAT_TYPE_SHORT, FORMAT_TYPE_LONG.

v. Time

$fieldset->addField('time', 'time', array(
'label' => Mage::helper('form')->__('Time'),
'class' => 'required-entry',
'required' => true,
'name' => 'time',
'onclick' => "",
'onchange' => "",
'disabled' => false,
'readonly' => false,
'after_element_html' => 'Time',
'tabindex' => 1
));

vi. Drop down

$fieldset->addField('select', 'select', array(
'label' => Mage::helper('form')->__('Select'),
'class' => 'required-entry',
'required' => true,
'name' => 'title',
'onclick' => "",
'onchange' => "",
'values' => array('-1'=>'Please Select..','1' => 'Option1','2' => 'Option2', '3' => 'Option3'),
'disabled' => false,
'readonly' => false,
'after_element_html' => 'Drop down',
'tabindex' => 1
));

  • Values: an array that contains all the options of the element. Those elements that have options must have this property

Another kind of drop-down:

$fieldset->addField('select2', 'select', array(
'label' => Mage::helper('form')->__('Select Type2'),
'class' => 'required-entry',
'required' => true,
'name' => 'title',
'onclick' => "",
'onchange' => "",
'values' => array(
'-1'=>'Please Select..',
'1' => array(
'value'=> array(
array('value'=>'2' , 'label' => 'Option2') , array('value'=>'3' , 'label' =>'Option3') ),
'label' => 'Size'),
'2' => array(
'value'=> array(
array('value'=>'4' , 'label' => 'Option4') , array('value'=>'5' , 'label' =>'Option5') ),
'label' => 'Color'),
),
'disabled' => false,
'readonly' => false,
'after_element_html' => 'Drop down',
'tabindex' => 1
));

vii. Multiselect

$fieldset->addField('multiselect', 'multiselect', array(
'label' => Mage::helper('form')->__('Select Type'),
'class' => 'required-entry',
'required' => true,
'name' => 'title',
'onclick' => "return false;",
'onchange' => "return false;",
'value' => '4',
'values' => array(
'-1'=> array(
'label' => 'Please Select..',
'value' => '-1'),
'1' => array(
'value'=> array(
array('value'=>'2' , 'label' => 'Option2') , array('value'=>'3' , 'label' =>'Option3')),
'label' => 'Size'
),
'2' => array(
'value'=> array(
array('value'=>'4' , 'label' => 'Option4') ,
array('value'=>'5' , 'label' =>'Option5') ),
'label' => 'Color'
),
),
'disabled' => false,
'readonly' => false,
'after_element_html' => 'Multiselect',
'tabindex' => 1
));</p>
<p style="text-align: justify;">

viii. Checkbox

$fieldset->addField('checkboxes', 'checkboxes', array(
'label' => Mage::helper('form')->__('Checkboxs'),
'name' => 'Checkbox',
'values' => array( array('value'=>'1','label'=>'Checkbox1'),
array('value'=>'2','label'=>'Checkbox2'),
array('value'=>'3','label'=>'Checkbox3'),
),
'onclick' => "",
'onchange' => "",
'value' => '1',
'disabled' => false,
'after_element_html' => 'Comments',
'tabindex' => 1
));

ix. Radio button

$fieldset->addField('radio2', 'radios', array(
'label' => Mage::helper('form')->__('Radios'),
'name' => 'title',
'onclick' => "",
'onchange' => "",
'value' => '2',
'values' => array(
array('value'=>'1','label'=>'Radio1'),
array('value'=>'2','label'=>'Radio2'),
array('value'=>'3','label'=>'Radio3')),
'disabled' => false,
'readonly' => false,
'after_element_html' => 'Radios button',
'tabindex' => 1
));

x. Password

$fieldset->addField('password', 'password', array(
'label' => Mage::helper('form')->__('Password'),
'class' => 'required-entry',
'required' => true,
'name' => 'title',
'onclick' => "",
'onchange' => "",
'style' => "",
'disabled' => false,
'readonly' => false,
'after_element_html' => 'Password',
));

Another kind of password field:

$fieldset->addField('obscure', 'obscure', array(
'label' => Mage::helper('form')->__('Obscure'),
'class' => 'required-entry',
'required' => true,
'name' => 'obscure',
'onclick' => "",
'onchange' => "",
'style' => "",
'value' => '123456789',
'after_element_html' => 'Obscure',
));

xi. Link

$fieldset->addField('link', 'link', array(
'label' => Mage::helper('form')->__('Link'),
'style' => "",
'href' => 'www.blog.magestore.com',
'value' => 'Magestore Blog',
'after_element_html' => 'Link'
));

xii. File upload

$fieldset->addField('file', 'file', array(
'label' => Mage::helper('form')->__('Upload'),
'value' => 'Upload',
'disabled' => false,
'readonly' => true,
'after_element_html' => 'File upload',
'tabindex' => 1
));

 

b. Custom form fields

In magento form, if you are not satisfied with available fields of Magento, you can totally modify them as you wish by using renderer for the field form as in the below example:

Advanced magento form in backend-magento form

 

 

As can be seen from the image, there is no form fields in Magento with checkboxes to enable or disable. So how did I do that? In fact, it’s very simple:
Follow the link:
app/code/local/{your_namespace}/{your_module}/block/adminhtml/{section}/edit/tab
to find the file Form.php
Please look at the example code below:

$fieldset->addField('name', 'text', array(
'label' => Mage::helper('lesson10')->__('Name'),
'class' => 'required-entry',
'required' => true,
'name' => 'name',
'onclick' => "alert('on click');",
'onchange' => "alert('on change');",
'disabled' => false,
'readonly' => true,
'after_element_html' => 'Textfield',
'tabindex' => 1
));
$form->getElement('name')->setRenderer(
Mage::app()->getLayout()->createBlock(
'lesson10/adminhtml_lesson10_edit_tab_renderer_name'));

To create render, you need to take 2 steps:
Step 1: Get the field to render and set renderer for it. Here, I chose field “name”:

$form->getElement('name')->setRenderer(Mage::app()->getLayout()
->createBlock(lesson10/adminhtml_lesson10_edit_tab_renderer_name);

Step 2: Create a renderer class in the file corresponding with the link in function
createBlock().
The link of this file is app/code/local/magestore/lesson10/block/adminhtml/lesson10/edit/tab/renderer/name.php. This class will declare function render

class Magestore_Lesson10_Block_Adminhtml_Lesson10_Edit_Tab_Renderer_Name extends Mage_Adminhtml_Block_Widget implements Varien_Data_Form_Element_Renderer_Interface {
public function render(Varien_Data_Form_Element_Abstract $element) {
$element-&gt;setDisabled(true);
$disabled = true;
$title = 'use_default';
$html = '
'.$element-&gt;getLabelHtml().'
';
$html.= '
'
.$element-&gt;getElementHtml().'
';
$html.= ' <input id="package_name_default" class="checkbox config-inherit" name="package_name_default" type="checkbox" value="1" />
<label class="inherit" title="'.$title.'" for="package_name_default">'.$title.'</label>
';
return $html;
}

Now, besides my “name” field in form, there is a checkbox to enable and disable:
Advanced magento form in backend-magento form

3. Custom buttons

a. Add custom buttons

In the Magento form container, you can add one or more buttons for different purposes. Below is the example image in form when I have added the button “Add new record”:
Advanced magento form in backend-magento form
And this is the instruction:

$this->_addButton('btn_add', array(
'label' => Mage::helper('adminhtml')->__(Add new record'),
'onclick' => 'setLocation(\'' . $this->getUrl('*/*/new') .'\')',
'class' => 'add',
),-1,3);

To make it clearer for you, the above code is added to the Edit.php file. You can find this file by the link: app/code/local/{your_namespace}/{your_module}/block/adminhtml/{section}
I will explain a bit about parameters of the function _addButton() :

protected function _addButton($id, $data, $level = 0, $sortOrder = 100, $area = 'header'){...}

$id: button id, This is the unique id for each button
$data: button parameter array, You can set attributes label, onclick and class for each button. Class can receive values such as delete, save, back, add, etc. Button display will differ based on this class. You can leave it blank to display a normal button.
$level 3: level, used to group buttons together and related to parameter 4 “sort_order”
$sortOrder: sort_order, used to arrange the orders of buttons of the same level.
$area: area, getting 2 values “header” and “footer”. The default value is header, but if you want to display button in the footer, you need to choose “footer”.

b. Delete custom buttons

In the above section, I have instructed you how to add a new button for your own purpose. To delete those buttons, you can simply delete the code used to add that button. The question is how to delete those available buttons in form of the System such as Save, Save and Continue Delete, Delete, etc? Below is the instruction:
Follow the link app/code/local/{your_namespace}/{your_module}/block/adminhtml/{section}/
To file Edit.php
In the function __construct() of the file Edit.php, I added this code:

public function __construct()
{
parent::__construct();
$this->_removeButton('delete');}

The Function _removeButton() has parameter which is id of button. If you want to delete any button, you can use the function removeButton. I advise you to follow this link to go to file Container.php to understand more clearly:
app/code/core/Mage/Adminhtml/Widget/ Container /
app/code/core/Mage/Adminhtml/Widget/Form/Container /
Because the base form of this function is quite simple, I will let you learn it by yourself.

c. Update custom buttons

Similcarly to deleting a button, Magento supports editing attributes of an available button so that you can control the number of buttons in form.
Steps are similar to those when you delete a button. A bit difference is that I added the following code in the function __construct():

public function __construct()
{
parent::__construct();
$this->_updateButton('save', 'label', Mage::helper('lesson10')->__('Apply'));}

In the above code, I have used the function _updateButton to change the label of the button “Save” in form to “Apply”.
Explanation about this function:
Method prototype:
protected function _updateButton($id, $key=null, $data){}
$id: button’s id.
$key: The properties of the button
$data: The value of the properties after update

That’s the end of the lesson 10, Advanced magento form in backend. So now, you have learned how to add tabs for form, add, edit and delete buttons in magento form according to your purpose. Hope you enjoy it! For more Mageno lesson, search the tag Magento Open Course or Magento Tutorial.

We will update Magento tutorials regularly, especially about Magento 2. Let’s subscribe to our blog to be the first one catch up with the latest news by leaving your email below.

Lesson 10: Advanced Magento form in Backend
4 (80%) 13 votes

Leave a Reply

Your email address will not be published. Required fields are marked *