Creating Content Fragments Programmatically (Best Practice)?
Hey all,
I'm working on a service will take data from an API &, in theory, write what is returned to a list of content fragments. I've gotten pretty far along, but I'm wondering if there's a better / cleaner way than my current approach.
Right now I have a function createContentFragment (seen below) which takes in a fullBranch object (data I want to turn into a content fragment), parentResource (self explanatory) and templateResource (template of the content fragment I want to turn this data into).
I noticed in the ContentFragment class that there's not a "setValues" or "setValue" function... it seems from the documentation that I would need to iterate over each contentElement & set each value individually. Obviously this is pretty annoying, so wondering if anyone has any suggestions on how to better / more easily set the ContentElement values than my intended approach? I also have a Store model (separate from the templateResource for now) which I was thinking I could possibly connect to the content fragment somehow? Not sure if this is possible. Any help is much appreciated!
private void createContentFragment(FullBranch fullBranch, Resource parentResource, Resource templateResource) {
try {
FragmentTemplate tpl = templateResource.adaptTo(FragmentTemplate.class);
if (tpl != null) {
ContentFragment newFragment = tpl.createFragment(parentResource, fullBranch.getKey(), fullBranch.getName());
Iterator < ContentElement > contentElement = newFragment.getElements();
//current long winded approach
while (contentElement.hasNext()) {
ContentElement contentElementObject = contentElement.next();
FragmentData value = contentElementObject.getValue();
String FieldName = contentElementObject.getName();
//would have to get the value from fullBranch using the FieldName and another function w/ a switch statement
value.setValue("test");
contentElementObject.setValue(value);
}
}
ObjectMapper().writeValueAsString(fullBranch));
} catch (Exception ex) {
LOGGER.error("Something went wrong" + ex.getMessage());
}
}