Expand my Community achievements bar.

Dive into Adobe Summit 2024! Explore curated list of AEM sessions & labs, register, connect with experts, ask questions, engage, and share insights. Don't miss the excitement.
SOLVED

How can we create Content fragment via code

Avatar

Employee

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.

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

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/Content...

 

View solution in original post

7 Replies

Avatar

Community Advisor

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/Content...

 

Hope this helps!

Thanks

Avatar

Employee

@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. 

Avatar

Employee

@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.

Avatar

Community Advisor

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());
            }
        }

    }

}

Vijayalakshmi_S_0-1633010802655.png

 

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/Content...

Avatar

Employee

 @Vijayalakshmi_S Thank you, it worked.

 

How can I set value of the element?

 

Avatar

Correct answer by
Community Advisor

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/Content...