0

One reason for my other question is the following use case: I want to create a TextImageModel which uses my ImageModel as an injected property and extends my TextModel:

@Model(adaptables = {SlingHttpServletRequest.class})
public class TextImageModel extends TextModel {

    @Inject
    private ImageModel image;
}

But this doesn't work. It should work when I would be using Resource as the adaptable, but I need the SlingHttpServletRequest in my ImageModel and TextModel as well:

@Model(adaptables = {SlingHttpServletRequest.class})
public class ImageModel {
    @SlingObject
    private SlingHttpServletRequest request;

    @SlingObject
    private Resource resource;
}

How can I inject the ImageModel using the request as adaptable? The image resource is a child resource with the name image

Community
  • 1
  • 1
Thomas
  • 6,325
  • 4
  • 30
  • 65

3 Answers3

2

Use the ModelFactory:

    ...
    import com.adobe.cq.wcm.core.components.models.Image;
    import org.apache.sling.models.factory.ModelFactory;
    ...
    @Inject 
    private ModelFactory modelFactory;
    @Self 
    private SlingHttpServletRequest request;

    private Image image;

    @PostConstruct 
    protected void postInit() {
            image = modelFactory.getModelFromWrappedRequest(request, resource.getChild("image"), Image.class);
    ...
    }

That should hopefully do the trick.

Oliver Gebert
  • 1,166
  • 1
  • 6
  • 20
1

You can use @Self instead of @Inject, but you will have the same resource in ImageModel as in TextImageModel. Not child "image" as you would like to. Afaik when adapting from Request, resource will be always read from Request.

@Model(adaptables = {SlingHttpServletRequest.class})
public class TextImageModel extends TextModel {

    @Self
    private ImageModel image;
}
rzasap
  • 346
  • 1
  • 6
0

If you want to inject from a specific other type than your adaptable then you can use @Inject @Via("resource")

more here: https://sling.apache.org/documentation/bundles/models.html#via

I'm not sure though whether that will work with a model and not a property

ub1k
  • 1,674
  • 10
  • 14