How to create a Liferay 7 structure programmatically?

浪子不回头ぞ 提交于 2019-12-04 20:43:44

It is a classNameId problem. Replacing DDLRecordSet with JournalArticle solves the problem, making the structure show up correctly in Liferay's Structures UI.

Code that works:

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

Map<Locale, String> nameMap = new HashMap<Locale, String>();
nameMap.put(Locale.JAPAN, "The name");
Map<Locale, String> descriptionMap = new HashMap<Locale, String>();
descriptionMap.put(Locale.JAPAN, "The description");

DDMForm ddmForm = null;
try {
    ddmForm = DDMUtil.getDDMForm(json);
} catch (PortalException e) {
    log.error("Exception when parsing structure JSON", e);
}

DDMFormLayout ddmFormLayout = DDMUtil.getDefaultDDMFormLayout(ddmForm);
long scopeClassNameId = PortalUtil.getPortal().getClassNameId(JournalArticle.class);
long parentStructureId = DDMStructureConstants.DEFAULT_PARENT_STRUCTURE_ID;
String storageType = StorageType.JSON.toString();
String structureKey = "my structure";

try {
    DDMStructure ddmStructure = DDMStructureLocalServiceUtil.addStructure(
        user.getUserId(), group.getGroupId(), parentStructureId,
        scopeClassNameId, structureKey,
        nameMap, descriptionMap, ddmForm, ddmFormLayout, storageType,
        DDMStructureConstants.TYPE_DEFAULT, serviceContext);
} catch (StructureDuplicateStructureKeyException e) {
    log.info("Skipping creation of structure that already exists");
} catch (PortalException e) {
    log.error("Exception when creating structure: " + structureDefinitionFilePath, e);
}

You forgot to initialize ServiceContext before call DDMStructureLocalServiceUtil. In the ServiceContext instance you should add default permission:

    ServiceContext context = new ServiceContext();
    context.setAddGroupPermissions(true);
    context.setAddGuestPermissions(true); 

By doing this before, you make sure that you can view the structure later.

There is a problem with your ServiceContext argument to the DDMStructureLocalServiceUtil.addStructure method. There are 2 ways you can set the context depending on from where you are trying to add the structure:

If you are invoking from the servlet that has access to the portlet request, use the following method:

   ServiceContextFactory.getInstance(className, portletRequest);

This would take care of all the necessary scope and permission.

If you are implementing it from anywhere else, the best way would be instantiate the ServiceContext and set at least the scopeGroupId:

ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(myGroupId);
serviceContext.setAddGroupPermissions(true);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!