Magento – magento add field dependency in admin form using a javascript function

javascriptmagento-1.8

In an custom admin form, I have added a custom tab and some custom fields to it. here I need to add field dependency for the fields as described below.

if the field zipbasedprice_isrange is set to yes, then I need to show other two fields & if it is set to no, then only one field should be shown.
How can I implement this using below form?

Field dependencies should be between zipbasedprice_isrange, zipbasedprice_zip, zipbasedprice_zip_from_zip & zipbasedprice_zip_to_zip.

I tried default field dependencies, but it did not work. Help me, how to implement this using a javascript function?

  $isRange = $fieldset->addField('zipbasedprice_isrange', 'select', array(
    'name' => 'zipbasedprice_isrange',
    'label' => Mage::helper('zipbasedprice')->__('Is Range?'),
    'values' => array(
        array(
            'value' => false,
            'label' => Mage::helper('zipbasedprice')->__('No'),
        ),
        array(
            'value' => true,
            'label' => Mage::helper('zipbasedprice')->__('Yes'),
        )
    ),
   'value' => false,
   'onchange' => 'onIsZipRangeChange()',
   'required' => false,
   'style' => 'width:275px',
  ));


$fieldset->addField('zipbasedprice_zip', 'text', array(
    'name' => 'zipbasedprice_zip',
    'label' => Mage::helper('zipbasedprice')->__('Zip Code'),
    'class' => 'input',
    'required' => true,
    'style' => 'width:268px',
    'value' => '*',
    'maxlength' => 6,
 ));


 $fieldset->addField('zipbasedprice_zip_from_zip', 'text', array(
    'name' => 'zipbasedprice_zip_from_zip',
    'label' => Mage::helper('zipbasedprice')->__('Zip Code From'),
    'class' => 'input',
    'required' => true,
    'style' => 'width:268px',
    'value' => '*',
    'maxlength' => 6,
 ));

  $fieldset->addField('zipbasedprice_zip_to_zip', 'text', array(
    'name' => 'zipbasedprice_zip_to_zip',
    'label' => Mage::helper('zipbasedprice')->__('Zip Code To'),
    'class' => 'input',
    'required' => true,
    'style' => 'width:268px',
    'value' => '*',
    'maxlength' => 6,
 ));

Best Answer

I tried default field dependencies, but it did not work.

Do you mean you tried this dependency trick?

$this->setChild('form_after', $this->getLayout()
    ->createBlock('adminhtml/widget_form_element_dependence')
        ->addFieldMap('zipbasedprice_isrange', 'zipbasedprice_isrange')
        ->addFieldMap('zipbasedprice_zip', 'zipbasedprice_zip')
        ->addFieldMap('zipbasedprice_zip_from_zip', 'zipbasedprice_zip_from_zip')
        ->addFieldMap('zipbasedprice_zip_to_zip', 'zipbasedprice_zip_to_zip')
        ->addFieldDependence('zipbasedprice_zip', 'zipbasedprice_isrange', false)
        ->addFieldDependence('zipbasedprice_zip_from_zip', 'zipbasedprice_isrange', true)
        ->addFieldDependence('zipbasedprice_zip_to_zip', 'zipbasedprice_isrange', true)
);
Related Topic