Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making magento admin field dependent on more than one value or field?

Tags:

magento

First of all I have already seen this question can a magento adminhtml field depend on more then one field or value? It talks about System/Configuration fields, which is not what I am looking for.

I am trying to create a form in the magento backend. I have a dropdown Dropdown with values 1, 2 and 3. I need the field X to be displayed when I select 1 or 2. How do I do this ?

I am able to display X depending on a single value of the dropdown, not for multiple values.

This is how I have done:

$this->setChild('form_after',$this->getLayout()->createBlock('adminhtml/widget_form_element_dependence')
            ->addFieldMap($X->getHtmlId(), $Xl->getName())
            ->addFieldMap($dropdown->getHtmlId(), $dropdown->getName())
            ->addFieldDependence($X->getName(), $dropdown->getName(), 1)
);

Where $x and $dropdown are variables which stores addField() result

like image 580
Hashid Hameed Avatar asked Apr 14 '14 10:04

Hashid Hameed


1 Answers

You can.

More Fields:
Just add more dependency:

->addFieldDependence($X->getName(), $dropdown_1->getName(), $value_dw_1)
->addFieldDependence($X->getName(), $dropdown_2->getName(),$value_dw_2)

More Values (same field):
You should pass an array of of values:

->addFieldDependence($X->getName(), $dropdown->getName(), array($value1,value2))

if $value1/$value2 are numbers it is better you cast them to string or it could not work properly:

->addFieldDependence($X->getName(), $dropdown->getName(), array((string)$value1,(string)value2))

There reason for this issue can be tracked down in js/mage/adminhtml/form.js in the method trackChange at one point you see this code :

...
// define whether the target should show up
    var shouldShowUp = true;
    for (var idFrom in valuesFrom) {
        var from = $(idFrom);
        if (valuesFrom[idFrom] instanceof Array) {
            if (!from || valuesFrom[idFrom].indexOf(from.value) == -1) {
                shouldShowUp = false;
            }
        } else {
            if (!from || from.value != valuesFrom[idFrom]) {
                shouldShowUp = false;
            }
        }
    }
....

you see that in case valuesFrom[idFrom] it is used indexOf to check if show the field or not, this cause problem because, it think, indexOf do a comparison taking care of the type and from.value it contains a string while in the array valuesFrom[idFrom] we have an array of numbers ...

This issue not occur in case of a single value because from.value != valuesFrom[idFrom] is not taking care of the type

like image 147
WonderLand Avatar answered Sep 22 '22 09:09

WonderLand