Did you know that when you’re creating a Magento Widget, you can show or hide specific fields according to the values of other fields? These are called dependencies, and are actually pretty easy to implement.
Our Magento widget
Let’s say we have a widget that allows your administrator to insert some content into your page. This content is optional, so your administrator is not required to fill these fields in. The basic approach could be something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<show_content> <required>0</required> <visible>1</visible> <label>Use hover</label> <type>select</type> <source_model>adminhtml/system_config_source_yesno</source_model> </show_content> <header> <required>0</required> <visible>1</visible> <label>Header</label> <type>text</type> </header> <content> <required>0</required> <visible>1</visible> <label>Inhoud</label> <type>textarea</type> </content> |
Add the dependencies
Now the thing with this, is that even though your administrator is not required to fill in this content, the fields still are shown. We can make this widget more user-friendly by adding a <depends> -node to some of the fields:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<show_content> <required>0</required> <visible>1</visible> <label>Use hover</label> <type>select</type> <source_model>adminhtml/system_config_source_yesno</source_model> </show_content> <header> <required>0</required> <visible>1</visible> <label>Header</label> <type>text</type> <depends> <show_content> <value>1</value> </show_content> </depends> </header> <content> <required>0</required> <visible>1</visible> <label>Inhoud</label> <type>textarea</type> <depends> <show_content> <value>1</value> </show_content> </depends> </content> |
Now this is a very basic example, but when source models get more complex, this solution can can come in quite handy. If you have a source model that returns more options for example, you can create whole forms with dependencies, giving your administrator a more clean and intuitive way to implement their widgets.
In conclusion
Widgets are a great way to allow your content editors in Magento to embed rich HTML content without worrying that they break your HTML layout. Taken in mind that you can also easily remove the wrapping paragraph around widgets they really are an underrated feature in Magento. Widget dependencies are just a small feature that make this even more simple for them.
Visitors give this article an average rating of 5.0 out of 5.
How would you rate this article?
★ ★ ★ ★ ★
Just wanted to add a note that a casual effort at implementing ‘depends’ with radio buttons didn’t seem to work.
Upon switching the type from ‘radios’ to ‘dropdown’ however everything works as expected.
Have you played around with this in Magento 2 already as well? It seems that the tag only works on text parameters there. Any idea? (Might be a bit off topic, but I thought I’d try it anyway).