Create a content fragment Programatically
Hi all
I am trying to create a content fragment programatically and I am not seeing the fragment being created in my node structure. Below is the code I compiled from different sources over the internet as I couldn't find a proper working example anywhere .
public void createContentFragment(final Resource parentRsc) {
try (ResourceResolver resourceResolver = resourceService.getResourceResolver(CommonConstants.SERVICE_USER)) {
Resource templateOrModelRsc = resourceResolver.getResource("/conf/demo/settings/dam/cfm/models/faq");
if (Objects.nonNull(templateOrModelRsc)) {
FragmentTemplate tpl = templateOrModelRsc.adaptTo(FragmentTemplate.class);
if (Objects.nonNull(tpl)) {
ContentFragment contentFragment = tpl.createFragment(parentRsc, "test", "A fragment description.");
if (null != contentFragment) {
Iterator<ContentElement> elements = contentFragment.getElements();
while (elements.hasNext()) {
ContentElement contentElement = elements.next();
contentElement.setContent("value", contentElement.getContentType());
}
}
Session session = resourceResolver.adaptTo(Session.class);
if (Objects.nonNull(session)) {
session.save();
}
}
}
} catch (Exception e) {
LOGGER.error("Exception ", e);
}
}
Update :- Thanks @shubhanshusi2 for the correct answer. Anyone facing a similar issue , please also refer my response https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/create-a-content-fragment-programatically/m-p/590594/highlight/true#M147438 , to understand what went wrong in my case.
Thanks
Veena