1

In Liferay 7, I have a structure, some FTL code, and I want to create a template from that, in a Java Liferay module (no portlet). Just like a human would do with the UI below, but programmatically:

Liferay 7 New Template

Note: The code proposed at How to create Structure & Template programmatically in Liferay 6 does not work, it results in Someone may be trying to circumvent the permission checker exceptions.

See also: How to create a Liferay 7 structure programmatically?

Nicolas Raoul
  • 58,567
  • 58
  • 222
  • 373

1 Answers1

1

This code takes a structure (DDMStructure) and successfully creates a template:

ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(group.getGroupId());
serviceContext.setAddGroupPermissions(true);
serviceContext.setAddGuestPermissions(true);
serviceContext.setWorkflowAction(WorkflowConstants.ACTION_PUBLISH);

String templateKey = "my template"; // Any name you want.

long classNameId = PortalUtil.getPortal().getClassNameId(DDMStructure.class);
long classPK = structure.getPrimaryKey();
long resourceClassNameId = PortalUtil.getPortal().getClassNameId(JournalArticle.class);
nameMap = Utils.createLocalesMap(templateKey);
descriptionMap = nameMap; // Use the same.
String type = "display";
String mode = "create";
String language = "ftl";
String script = null;
try {
    script = new String(Files.readAllBytes(Paths.get("/path/to/my/template.ftl")));
} catch (IOException e) {
    log.error("Exception when reading template: " + templateDefinitionFilePath, e);
}

try {
    DDMTemplate template = DDMTemplateLocalServiceUtil.addTemplate(
        user.getUserId(), group.getGroupId(), classNameId, classPK,
        resourceClassNameId, nameMap, descriptionMap,
        type, mode, language, script, serviceContext);
} catch (PortalException e) {
    log.error("Exception when creating template: " + templateDefinitionFilePath, e);
    return false;
}
Nicolas Raoul
  • 58,567
  • 58
  • 222
  • 373
  • The "Someone may be trying to circumvent the permission checker" is a exception the permission checker throws.. may be you or some service internally uses the secured api ... – André Aug 21 '18 at 09:45