Add dependent fields

Sometime, you want to add dependent fields on frontend. There are some ways to do that, you can use jquery or custom script. However, in this small tutorial, we will use default Magento 2 library. That library is “mage/adminhtml/form”, you can use it in javascript or phtml files.

Following below is a code sample:

    require(["mage/adminhtml/form"], function() {
        try {
            var jsonobject = '{{"favourite_game":{“gender":{"values":["male"],"negative":false}}}}' ;
            new FormElementDependenceController(JSON.parse(jsonobject));
        } catch (err) {
            console.log('Could not add dependent fields: ' + err.message);


If you use jquery, you need to handle each dependent field or write a smart method to handle with structure data automatically. FormElementDependenceController accepts a JSON object. For example:

Complex conditions

{"favourite_game":{“gender":{"values":["male"],"negative":false}, “age”: {"values":["gt18"],"negative":false} }}

{"favourite_game":{“gender":{"values":["male"],"negative":false}} , "favourite_music":{“gender":{"values":["female"],"negative":false}}}

Multi level conditions:

{"favourite_game":{“gender":{"values":["male"],"negative":false}}, "gender":{“product_type":{"values":["heath_care"],"negative":false}}}

The most advantage of this solution is you can define conditions from server side, then encode data and the system will do remain parts.  



Leave a Reply

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