AEM: Is it possible to test if parsys has content without extending the parsys?

2.8k views Asked by At

Is it possible to test if a parsys has content without extending and creating a custom version of the parsys? Link to some documentation to the parsys properties is accepted as well.

I have a parsys that I need removed in the event that it is empty given that some classes applied to the parsys are affecting the layout.

2

There are 2 answers

0
mish On

You could extract the sling resource of the parsys and then check if it has children:

boolean isParsysEmpty = !resourceResolver.resolve("/path/to/your/parsys").hasChildren();

See the JavaDoc: https://docs.adobe.com/docs/en/aem/6-0/develop/ref/javadoc/org/apache/sling/api/resource/Resource.html#hasChildren%28%29

0
bstockwell On

You have to use a USE API class for this.

The hasChildren() function referenced above won't work in a js use api class (which is very annoying -- here's the implementation of resource available in the js usp api: http://svn.apache.org/viewvc/sling/trunk/bundles/scripting/javascript/src/main/java/org/apache/sling/scripting/javascript/wrapper/ScriptableResource.java?revision=1674092&view=markup).

Here is a solution that uses the ResourceUtils.js and q.js to test to see if a provided parsys exists:

sightly:

<div data-sly-use.hasChildren="${'hasChildren.js' @ parsys='MainContent', page=currentPage}" data-sly-unwrap>
  <div data-sly-test="${wcmmode.edit || hasChildren}" data-sly-unwrap>
      <div data-sly-resource="${'MainContent' @ resourceType='foundation/components/parsys'}"></div>
  </div>
</div>

hasChildren.js

"use strict";
use(["/libs/wcm/foundation/components/utils/ResourceUtils.js", "/libs/sightly/js/3rd-party/q.js"], function (ResourceUtils, Q) {

    var childPromise = Q.defer();

    if(this.page.getContentResource(this.parsys) != null) {
        ResourceUtils.getResource(this.page.getContentResource(this.parsys).getPath()).then(function(res) { 
            res.getChildren().then(function (childItems) {
                return childPromise.resolve(childItems.length > 0);
            }, function (error) {
            });
        }, function (error) {
        });
        return childPromise.promise;
    }
});