Expand my Community achievements bar.

Guidelines for the Responsible Use of Generative AI in the Experience Cloud Community.
SOLVED

HTL cannot access my custom Sling Model.

Avatar

Level 1

Hello.

 

HTL cannot access my simple Java Sling Model.

Here is my Sling Model sample. (Skipped the Interface because it is really simple.)

 

@Model(adaptables = Resource.class, adapters = MyComponent.class)
public class MyComponentImpl implements MyComponent{
    @ValueMapValue(name = "fragmentPath", injectionStrategy = InjectionStrategy.OPTIONAL)
    private String cfPath;

    @SlingObject
    private ResourceResolver resourceResolver;
    
    private ContentFragment cf;

    @PostConstruct
    public void init() {
        cf = resourceResolver.resolve(cfPath).adaptTo(ContentFragment.class);
    }

    
    public String getTitle() {
        return cf.getElement("title").getContent();
    }
}

 

  and here is my HTL which call MyComponent's method.

 

<sly data-sly-use.templates="core/wcm/components/commons/v1/templates.html"
     data-sly-use.model="foo.bar.core.models.MyComponent" />

<div data-sly-test="${model.title.length > 0}">
    <span>${model.title @ context='html'}</span>
</div>

<sly data-sly-call="${templates.placeholder @ isEmpty=!properties.fragmentPath}"></sly>

 

 

and result...

 

org.apache.sling.scripting.sightly.render.ObjectModel Cannot access method title on object foo.bar.core.models.impl.MyComponentImpl@205d4d6f

 

 

This happens on AEM Cloud. On my local SDK, It's fine.

Please help me.

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

comment out

cf = resourceResolver.resolve(cfPath).adaptTo(ContentFragment.class);

 

 

change method to 

    public String getTitle() {
        return "test";
    }


and then see if the Sling Model returns anything. It might be because of your resolved Object is not correct form the resolver. The initiation of the Sling Model looks just fine.

 

View solution in original post

2 Replies

Avatar

Correct answer by
Community Advisor

comment out

cf = resourceResolver.resolve(cfPath).adaptTo(ContentFragment.class);

 

 

change method to 

    public String getTitle() {
        return "test";
    }


and then see if the Sling Model returns anything. It might be because of your resolved Object is not correct form the resolver. The initiation of the Sling Model looks just fine.

 

Avatar

Community Advisor

Hi @watopin,

 

Try to use this:

 

 private Optional<ContentFragment> contentFragment;

@PostConstruct
    public void init() {
        contentFragment = Optional.ofNullable(resource.adaptTo(ContentFragment.class));
    }

And if this does not work too, define to refresh your bundles, as suggested here

https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/how-can-resolved-quot-org-...

 

Thanks,

Chitra