“What can I do to restrict the selection of my pathfield widget? I don’t want to do it simply based on the rootPath, I know you did this before, can you teach it to me?” This is a question that my team mates frequently ask me, so I decided to create a post because maybe you need the answer too.
When you work in your first days or first components with the Pathfield widget, you may only want to restrict your search path. Doing it by a given rootPath property is enough, but I am sure you will get to a point in which you will want to restrict the possibilities further, maybe based on some property, maybe based on some template, and so on.
The procedure is really simple, you only have to define a OSGi Service which inherits from AbstractNodePredicate and implements the interface Predicate. The important thing here is to ensure you redefine the method evaluate to return true to the pages you want to display in your pathfield and false otherwise. Add a property with a property name so you can refer to it in your dialog and you are ready to go.
This could be a start point for your predicate in Java:
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 30 31 |
import javax.jcr.Node; import org.apache.commons.collections.Predicate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Service; import com.day.cq.commons.predicate.AbstractNodePredicate; /** * Example of how to create a predicate. * * @author almagrosoteloa * */ @Component @Service @Property(name = "predicate.name", value = "myPredicate") public class MyPredicate extends AbstractNodePredicate implements Predicate { @Override public boolean evaluate(final Node node) { return isInPredicate(node); } /* Auxiliary methods */ private boolean isInPredicate(final Node node) { // Do your stuff } } |
And now the reference in your dialog:
1 2 3 |
var pathfield = new CQ.form.PathField({ predicate: "myPredicate" }) |
I hope this helps you in your everyday work 😉
Hello
I am new to CQ5. Where do exactly I place the MyPredicate.java file?
It is strange that something so obvious as filtering (e.g by resourceType or path) is not included by default on the component and we have to use non documented ways.
Hi!
It is not so important where you place it, as you register the predicate as an OSGi Service, so it will depend on your project structure. The important thing here is to use in your dialog the same name you entered for the predicate.name property, in this case, myPredicate.
Regards,
Alberto