May 5, 2020
Estimated Post Reading Time ~

Add Listeners to Widgets in CQ5

When we build a dialog in CQ5, we could need to define a custom action responding to a specific event.

Imagine for example that you need to copy the content of one field into another one or maybe you need to show/hide a specific field depending on the value of another field. These are typical examples where you need to define a listener in a CQ5 dialog in order to do something.

So let’s see how to define a custom listener in a few steps. In the following example, I will show how you can show/hide a field in a dialog, depending on the value of another field.

First of all, we need to add an id (itemId) to the element that we need show/hide, in order to be able to select it by JS. In our example, I set this id as idField.
Then we need to add a listener to the field that we need to evaluate the value:
If the value is 0, we hide the field with the specified id and we set the field as not required
If the value is 1, we show the field with the specified id and we set the field as required

Here you can find the complete dialog example.
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
jcr:primaryType="cq:Dialog"
height="{Long}600"
helpPath="en/cq/current/wcm/default_components.html#Text"
title="Text"
width="{Long}700"
xtype="dialog">
<items jcr:primaryType="cq:WidgetCollection">
<tabs jcr:primaryType="cq:TabPanel">
<items jcr:primaryType="cq:WidgetCollection">>
<item1
jcr:primaryType="cq:Widget"
title="Tab Title"
xtype="panel">
<items jcr:primaryType="cq:WidgetCollection">
<option1
jcr:primaryType="cq:Widget"
fieldLabel="Options"
name="./option"
type="radiogroup"
defaultValue="0"
xtype="selection">
<options jcr:primaryType="cq:WidgetCollection">
<automatic
jcr:primaryType="nt:unstructured"
text="Hide Field"
value="0"/>
<blank
jcr:primaryType="nt:unstructured"
text="Show field"
value="1"/>
</options>
<listeners jcr:primaryType="nt:unstructured" selectionchanged="function(comp, val, isChecked) {
var panel = comp.findParentByType('panel');
var link = panel.getComponent('idField');
if(val == 1){
link.show();
link.allowBlank = false;
}else{
link.hide();
link.allowBlank = true;
}
}"/>
</option1>
<link1
itemId="idField"
jcr:primaryType="cq:Widget"
fieldDescription="Insert here the path of the product"
fieldLabel="Path"
name="./link1"
xtype="pathfield">
</link1>
</items>
</item1>
</items>
</tabs>
</items>
</jcr:root>

You can check all the documentation about widgets, event and more at https://docs.adobe.com/docs/en/cq/5-5/widgets-api/index.html (in this case for CQ5.5)


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.