How can we create Content fragment via code | Community
Skip to main content
Adobe Employee
September 30, 2021
Solved

How can we create Content fragment via code

  • September 30, 2021
  • 6 replies
  • 7492 views

The requirement to create content fragment via Java code (Utility or servlet). How can I achieve this?

 

https://aemdeveloper.wordpress.com/2017/08/22/create-access-the-content-fragment-programmatically/

 

referred this link to create the CF but there's no output. Please let me know if there's any method to achieve this.

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by Vijayalakshmi_S

Below is the snippet for setting value to the Element - I have one Single Text element and Multi Line Text element as part of my model. Get that element using its "fieldName" (that you provided while creating CFM) and then set the content. 

 

Note : 

Any updates/persists to content fragment calls for a commit unless specified otherwise.

 

if (contentFragment != null) {              

                    ContentElement textField = contentFragment.getElement("textField");
                    LOG.debug("Textfield content type={} and content={}", textField.getContentType(),textField.getContent());
                    textField.setContent("Text/Single line text content inside the created CF", "text/plain");
                    
                    ContentElement description = contentFragment.getElement("description");
                    LOG.debug("description content type={} and content={}", description.getContentType(),description.getContent());
                    description.setContent("Description/Multi line text content inside the created CF", "text/plain");
                    resourceResolver.commit();
                }

For any other operations on the content fragment, you can refer the API doc - https://www.adobe.io/experience-manager/reference-materials/6-5/javadoc/com/adobe/cq/dam/cfm/ContentFragment.html

 

6 replies

Asutosh_Jena_
Community Advisor
Community Advisor
September 30, 2021

Hi @keerthana_h_n 

 

Using below approach you should be able to create content fragments.

 

template.adaptTo(FragmentTemplate.class).createFragment(parent, name, title)

 

Parameters:
parent - The parent for the new content fragment
template - The template to be used
name - The (technical) name of the fragment to be created
title - The (human-readable) title of the fragment to be created


Returns:
The newly created content fragment

 

Reference:

https://www.adobe.io/experience-manager/reference-materials/6-5/javadoc/com/adobe/cq/dam/cfm/ContentFragmentManager.html

 

Hope this helps!

Thanks

Adobe Employee
September 30, 2021

@asutosh_jena_ Yeah I tried but getting exception saying invalid template. 

"/conf/test-cf-model/settings/dam/cfm/models/test-cookie-fragment-model"

this is my template and using the resource of this path to create fragment. 

Bhuwan_B
Community Advisor
Community Advisor
September 30, 2021
Adobe Employee
September 30, 2021

@bhuwan_b tried using both way 

templateRes.adaptTo(FragmentTemplate.class).createFragment(parentFolder, "custom-name", "Custom Title");

 fragmentManager.create(parent, template, “my-test-fragment”, “My Test Fragment”);

The code runs fine but there is no content fragment created in the DAM.

Vijayalakshmi_S
September 30, 2021

Hi @keerthana_h_n,

It calls for explicit resourceResolver.commit() to persist the creation in the repository.

 

Below code works fine. Executing again will create the content fragment with name as mentioned in the code with "-1"  and so on. Eg : in this case, it is sample-cf-programmatically-1 and so on.. )

 

(For quicker testing created it as doGet and path registration)

package com.aem.demoproject.core.servlets;

import com.adobe.cq.dam.cfm.ContentFragment;
import com.adobe.cq.dam.cfm.ContentFragmentException;
import com.adobe.cq.dam.cfm.FragmentTemplate;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.IOException;

@Component(service = Servlet.class, property = {
        "sling.servlet.methods=" + HttpConstants.METHOD_GET,
        "sling.servlet.paths=" + "/bin/cf/create"})
public class ContentFragmentCreation extends SlingSafeMethodsServlet {
    private final Logger LOG = LoggerFactory.getLogger(this.getClass());

    @Override
    protected void doGet(final SlingHttpServletRequest req, final SlingHttpServletResponse resp)
            throws ServletException, IOException {
        ResourceResolver resourceResolver = req.getResourceResolver();
        Resource templateResc = resourceResolver.resolve("/conf/we-retail/settings/dam/cfm/models/cf-model-demo");
        Resource cfParentResc = resourceResolver.resolve("/content/dam/we-retail/en/stores");
        if (templateResc != null && cfParentResc != null) {
            try {
                FragmentTemplate fragmentTemplate = templateResc.adaptTo(FragmentTemplate.class);
                ContentFragment contentFragment = fragmentTemplate.createFragment(cfParentResc, "sample-cf-programmatically", "Sample CF Programmatically");
                resourceResolver.commit();
                if (contentFragment != null) {
                    LOG.info("Created CF Title={}", contentFragment.getTitle());
                    LOG.info("Created CF name={}", contentFragment.getName());
                }               

            } catch (ContentFragmentException e) {
                LOG.error("ContentFragmentException={}", e.getMessage());
            }
        }

    }

}

 

Note : ContentFragmentManager.create(..) is deprecated. Recommendation is to use the above

https://www.adobe.io/experience-manager/reference-materials/6-5/javadoc/com/adobe/cq/dam/cfm/ContentFragmentManager.html#create-org.apache.sling.api.resource.Resource-org.apache.sling.api.resource.Resource-java.lang.String-java.lang.String-

Adobe Employee
September 30, 2021

 @vijayalakshmi_s Thank you, it worked.

 

How can I set value of the element?

 

Vijayalakshmi_S
Vijayalakshmi_SAccepted solution
September 30, 2021

Below is the snippet for setting value to the Element - I have one Single Text element and Multi Line Text element as part of my model. Get that element using its "fieldName" (that you provided while creating CFM) and then set the content. 

 

Note : 

Any updates/persists to content fragment calls for a commit unless specified otherwise.

 

if (contentFragment != null) {              

                    ContentElement textField = contentFragment.getElement("textField");
                    LOG.debug("Textfield content type={} and content={}", textField.getContentType(),textField.getContent());
                    textField.setContent("Text/Single line text content inside the created CF", "text/plain");
                    
                    ContentElement description = contentFragment.getElement("description");
                    LOG.debug("description content type={} and content={}", description.getContentType(),description.getContent());
                    description.setContent("Description/Multi line text content inside the created CF", "text/plain");
                    resourceResolver.commit();
                }

For any other operations on the content fragment, you can refer the API doc - https://www.adobe.io/experience-manager/reference-materials/6-5/javadoc/com/adobe/cq/dam/cfm/ContentFragment.html