Magento – How to add fieldset in Magento custom admin form when field select value changed

adminformfieldsetsformsjavascriptmagento-1

I have a select field like this in my costum magento admin form

$fieldset->addField(
    'category_id',
    'select',
    array(
        'id'    => 'lazadaCategory',
        'label'  => Mage::helper('test_sellercenter')->__('Category '),
        'name'   => 'status',
        'values' => Mage::helper('test_sellercenter/dropdown')->getLazadaCategories(),
        'class' => 'required-entry',
    )
);

and when the select value change i need to add another fields below this select field (not like toogle show/hide just add), for example like this field

$fieldset->addField(
    'listing_name',
    'text',
    array(
        'label' => Mage::helper('test_sellercenter')->__('Listing Name'),
        'name'  => 'listing_name',
        'required'  => true,
        'class' => 'required-entry',

    )
);

is there a way to do this in magento? for example like this add field example

Best Answer

For that you can use field dependencies feature of Magento, like here is the example

$status = $fieldSet->addField('status', 'select', array(
    'label'     => Mage::helper('module')->__('Status'),
    'name'      => 'status',
    'values'    => array(
        'Approved' => 'Approved',
        'Denied'   => 'Denied'
    )
));

$denyReason = $fieldSet->addField('denial_reason', 'textarea', array(
    'label'     => Mage::helper('module')->__('Denial Reason'),
    'name'      => 'denial_reason'
));

And add your dependencies

$this->setForm($form);
$this->setChild('form_after', $this->getLayout()->createBlock('adminhtml/widget_form_element_dependence')
    ->addFieldMap($status->getHtmlId(), $status->getName())
    ->addFieldMap($denyReason->getHtmlId(), $denyReason->getName())                     
    ->addFieldDependence(
        $denyReason->getName(),
        $status->getName(),
        'Denied'
    )
);

$denyReason field only display If status is set to Denied. According to this you can define your field dependencies.