AEM CQ 56 - Add Template as Options Predicate in SiteAdmin Search Panel


Goal


CQ SiteAdmin Search Panel (http://localhost:4502/siteadmin) lets author filter content using Template name. Default template filter (predicate) is a textbox, with this customization we hide ootb filter and add a new options filter showing available /apps/ templates in CQ system. Package install, Source code and Demo available for download




Prerequisites


If you are new to CQ

1) Read this post on how to create a sample page component

2) Read this post on how to setup your IDE and create an OSGI component

Solution


1) Create a servlet apps.mysample.searchpanel.GetTemplates for getting the templates in CQ system as json, readable by CQ.wcm.OptionsPredicate and install it as OSGI component. Add the following code in servlet

package apps.mysample.searchpanel;

import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.commons.json.io.JSONWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.Session;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.servlet.ServletException;
import java.io.IOException;

@SlingServlet(
        paths="/bin/mycomponents/searchpanel/templates",
        methods = "GET",
        metatype = false,
        label = "Get Templates Servlet"
)
public class GetTemplates extends SlingAllMethodsServlet {
    private static final Logger log = LoggerFactory.getLogger(GetTemplates.class);

    @Override
    protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        JSONWriter jw = new JSONWriter(response.getWriter());

        try{
            ResourceResolver resolver = request.getResourceResolver();
            Session session = resolver.adaptTo(Session.class);
            QueryManager qm = session.getWorkspace().getQueryManager();

            String stmt = "select * from cq:Template where jcr:path like '/apps/%' order by jcr:title";
            Query q = qm.createQuery(stmt, Query.SQL);

            NodeIterator results = q.execute().getNodes();
            Node node = null ; Property title = null;

            jw.object();
            jw.key("jcr:title");
            jw.value("Templates");

            while(results.hasNext()){
                node = results.nextNode();

                if(!node.hasProperty("jcr:title")){
                    continue;
                }

                title = node.getProperty("jcr:title");

                jw.key(node.getPath());
                jw.object();
                jw.key("jcr:title");
                jw.value(title.getString());
                jw.key("tagId");
                jw.value(node.getPath());
                jw.endObject();
            }

            jw.endObject();
        }catch(Exception e){
            log.error("Error getting templates",e);
            throw new ServletException(e);
        }
    }
}

2) Login to CRXDE Lite, create folder (nt:folder) /apps/searchpaneltemplate

3) Create clientlib (type cq:ClientLibraryFolder/apps/searchpaneltemplate/clientlib and set a property categories of String type to cq.widgets

4) Create file ( type nt:file ) /apps/searchpaneltemplate/clientlib/js.txt, add the following

                         addtemplate.js

5) Create file ( type nt:file ) /apps/searchpaneltemplate/clientlib/addtemplate.js, add the following code

CQ.Ext.ns("MyClientLib");

MyClientLib.SiteAdminSearchPanel = {
    SA_SEARCH_PANEL_SEARCH: "cq-siteadminsearchpanel-search",
    SA_SEARCH_PANEL_GRID: "cq-siteadminsearchpanel-grid",

    addTemplateOptions: function(){
        var panel = CQ.Ext.getCmp(this.SA_SEARCH_PANEL_SEARCH);

        //search for template field in search  panel
        var component = panel.findBy(function(comp){
            return comp["propertyName"] == "jcr:content/cq:template";
        }, panel);

        //hide ootb template field in search panel
        component[0].setVisible(false);

        //add the templates predicate
        var templates = new CQ.wcm.OptionsPredicate({
            collapse: "level0",
            hideLabel: true,
            "jcr:primaryType" : "cq:Widget",
            optionsPaths: ["/bin/mycomponents/searchpanel/templates.json"],
            "propertyName":"jcr:content/cq:template"
        });

        panel.add(templates);

        var subPanel = templates.findBy(function(comp){
            return comp["subPanel"] instanceof CQ.Ext.Panel ;
        }, panel)[0];

        //get the checkboxes
        var cBoxes = subPanel.findBy(function(comp){
            return comp instanceof CQ.Ext.form.Checkbox;
        }, panel);

        //add toottip showing template path
        CQ.Ext.each(cBoxes, function(box){
            box.on('afterrender', function(){
                CQ.Ext.QuickTips.register({
                    target: this.id,
                    text: this.inputValue,
                    dismissDelay: 2000
                });
            });
        });

        panel.doLayout();
    }
};

(function(){
    if(window.location.pathname == "/siteadmin"){
        var SA_INTERVAL = setInterval(function(){
            var s = MyClientLib.SiteAdminSearchPanel;
            var grid = CQ.Ext.getCmp(s.SA_SEARCH_PANEL_GRID);

            if(grid && (grid.rendered == true)){
                clearInterval(SA_INTERVAL);
                s.addTemplateOptions();
            }
        }, 250);
    }
})();




No comments:

Post a Comment