Magento – Admin form fetch values from dropdown

adminformdependency

I have created a custom admin module and in my Model/Nic.php, I have created below function

public function toOptionArray()
{
    $nicCollection = Mage::getModel('nic/nic')->getCollection();

    $nicarray = array();
    $i = 0;
    foreach ($nicCollection as $nicList) {
        $nicarray[] = array('-1'=>'Please Select','value'=>$nicList['nic_id'],'label'=>$nicList['nic_name'],'nic_cost'=>$nicList['nic_cost']);
    }

     return $nicarray;
}

which gives me below array values when printed $nicarray,

Array
(
    [0] => Array
        (
            [-1] => Please Select
            [value] => 1
            [label] => America
            [nic_cost] => 3.4
        )

    [1] => Array
        (
            [-1] => Please Select
            [value] => 2
            [label] => China
            [nic_cost] => 2.3
        )

    [2] => Array
        (
            [-1] => Please Select
            [value] => 3
            [label] => India
            [nic_cost] => 4.5
        )

    [3] => Array
        (
            [-1] => Please Select
            [value] => 4
            [label] => Japan
            [nic_cost] => 2.5
        )

)

Now in my admin form, I am able to fetch values in dropdown format usign toOptionArray.

$fieldset->addField('nic_id', 'select', array(
    'label'     => Mage::helper('nic')->__('Nic'),
    'class'     => 'required-entry',
    'values'    => Mage::getModel('nic/nic')->toOptionArray(),
    'name'      => 'nic_id',
));


$fieldset->addField('nic_cost', 'text', array(
    'label'     => Mage::helper('coffeecomponents')->__('Nic Cost'),
    'class'     => 'required-entry',
    'required'  => true,
    'name'      => 'nic_cost',
));

What I need to do is to fetch the value of nic_cost in Nic Cost input field based on what is selected from dropdown.

So if admin selects America from dropdown, then in Nic Cost input field the value should be populated with 3.4 (as shown in array) and if China then value should be 2.3

How can I change value dynamically when option is changed/selected from dropdown ?

Best Answer

Make your method look like this:

public function toOptionArray()
{
    $nicCollection = Mage::getModel('nic/nic')->getCollection();

    $nicarray = array(
         array(
            'value'=>-1, 
            'label'=>'Please Select'
         )
    );
    foreach ($nicCollection as $nicList){
        $nicarray[] = array(
               'value'=>$nicList['nic_cost'],
               'label'=>$nicList['nic_name']
        );
    }
    return $nicarray;
}