AEM - Fetching Multifield Values Using Sling Model




In 6.4 and above multifield values get stored as a node. In order to fetch those values in sling models earlier we used to write methods which include node/resource iterators, but now there is a simple and quick way to do so.

Lets see how to do that : 

Let us suppose we have created a mulfield named "socialLinks " which has "socialMedia" & "socialMediaLink" properties. 


Now in order to read these properties, create a model class for your component which has socialLinks as a multifield . 

@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)

public class Model {

    /** The social links. */
    @Inject
    private List<SocialLinkModel> socialLinks;

    /**
     * Gets the social links.
     *
     * @return the social links
     */
    public List<SocialLinkModel> getSocialLinks() {
        return new ArrayList<>(socialLinks);
    }

}

Create another class named SocialLinkModel.java and get value of  "socialMedia" & "socialMediaLink" using inject or valueMap.

@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class SocialLinkModel {

    /** The social media. */
    @ValueMapValue
    private String socialMedia;

    /** The social media link path. */
    @ValueMapValue
    private String socialMediaLink;

    /**
     * Gets the social media.
     *
     * @return the social media
     */
    public String getSocialMedia() {
        return socialMedia;
    }

    /**
     * Gets the social media link path.
     *
     * @return the social media link path
     */
    public String getSocialMediaLink() {
        return socialMediaLink;
    }

}

In your html file write the below code to display values:

<sly data-sly-list.socialLinks= "${model.socialLinks}">
    ${socialLinks.socialMedia}
     ${socialLinks.socialMediaLink}
</sly>

    Hope this helps!!

    Happy Coding 🙏

If you like my post and find it helpful, you can buy me a coffee.


Comments

  1. Soo good and please tell about how to remove popup messages in aem

    ReplyDelete
    Replies
    1. Thank you :)
      Which pop up message are you talking about , can you please elaborate?

      Delete
  2. Nice article in a simple way 👍

    ReplyDelete
  3. Nice article in a simple way 👍

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Hi, can you please tell how to fetch an image or images using sling model

    ReplyDelete
    Replies
    1. Get by using @ValueMapValue the property with the same name you are adding it in the dialog. For more information please attach the screenshot of property from crxde

      Delete

Post a Comment