Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AEM Sling Model example for handling multi-fields components and exporting it into model.json while working with SPA
package com.surajkamdi.aem.core.models;
import com.adobe.cq.export.json.ComponentExporter;
import com.adobe.cq.export.json.ExporterConstants;
import java.util.Collection;
import javax.annotation.PostConstruct;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Exporter;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.ChildResource;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;
/**
* Multifield Example model.
* @author suraj.kamdi
*/
@Model(
adaptables = SlingHttpServletRequest.class,
adapters = ComponentExporter.class,
defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL,
resourceType = MultifieldExampleModel.RESOURCE_TYPE)
@Exporter(
name = ExporterConstants.SLING_MODEL_EXPORTER_NAME,
extensions = ExporterConstants.SLING_MODEL_EXTENSION)
public class MultifieldExampleModel implements ComponentExporter {
protected static final String RESOURCE_TYPE = "/app/sample-project/components/multifield-component";
@ValueMapValue(name = "streetNumber")
private String streetNumber;
@ValueMapValue(name = "street")
private String street;
@ValueMapValue(name = "state")
private String state;
@ValueMapValue(name = "country")
private String country;
//Multifield Child Resource for social links
@ChildResource(name = "socialLinks")
Collection<SocialLinksModel> socialLinks;
@PostConstruct
protected void init() {
socialLinks = CollectionUtils.emptyIfNull(this.socialLinks);
}
public String getStreetNumber() {
return streetNumber;
}
public String getStreet() {
return street;
}
public String getState() {
return state;
}
public String getCountry() {
return country;
}
public Collection<SocialLinksModel> getSocialLinks() {
return socialLinks;
}
@Override
public String getExportedType() {
return RESOURCE_TYPE;
}
}
package com.surajkamdi.aem.core.models;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;
/**
* Social Links Sling Model. (Multifield Child Resource for social links)
* @author suraj.kamdi
*/
@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class SocialLinksModel {
@ValueMapValue(name = "socialSiteName")
private String socialSiteName;
@ValueMapValue(name = "socialSiteUrl")
private String socialSiteUrl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment