Liferay7.2 如何通过代码为Web Content(网页内容)添加关联分类?
Liferay 7 网页内容绑定分类失败解决方案
核心问题定位
- 调用
updateAsset时参数类型错误:你定义的categoryId本身就是long[]类型,代码中额外套了一层new long[]{categoryId}属于语法错误,实际传入的不是合法的分类ID数组,会导致参数解析失败。
- 调用
- 分类匹配逻辑存在风险:直接使用
category.getName().equals(index.getLaboratorioNombre())匹配,若站点配置多语言,getName()默认返回当前locale下的分类名称,和你创建分类时传入的名称可能存在不匹配的情况,可能匹配到无效ID。
- 分类匹配逻辑存在风险:直接使用
- 无需单独调用更新接口:更稳妥的方式是在创建网页内容时直接通过
serviceContext注入分类ID,避免二次更新的异常。
- 无需单独调用更新接口:更稳妥的方式是在创建网页内容时直接通过
修正方案
步骤1:修正参数错误
直接把原有updateAsset调用的参数替换为你的categoryId数组即可:
// 错误写法 // JournalArticleLocalServiceUtil.updateAsset(userId, article, new long[]{categoryId}, null, null, null); // 正确写法 JournalArticleLocalServiceUtil.updateAsset(userId, article, categoryId, null, null, null);
步骤2:推荐更稳妥的实现方式(无需额外调用updateAsset)
在调用addArticle创建网页内容之前,直接把分类ID设置到serviceContext中,创建时自动完成绑定:
// 匹配到分类ID后添加这行代码 serviceContext.setAssetCategoryIds(categoryId); // 原有创建文章的逻辑,创建时自动关联分类 article = JournalArticleLocalServiceUtil.addArticle( userId, groupId, folderId, titleMap, descriptionMap, content, ddmStructureKey, ddmTemplateKey, serviceContext); // 不需要再单独调用updateAsset
额外校验项
- 可打印日志确认你匹配到的
categoryId[0]是否为有效值,若为0说明分类匹配逻辑未找到对应分类,需要检查词汇表ID、分类名称、站点ID是否一致。 - 确认你使用的词汇表是当前站点(和文章groupId一致)下的词汇表,若使用全局站点词汇表,需要额外配置全局分类可关联到子站点的权限。
优化建议
创建分类时直接接收返回的分类对象获取ID,避免遍历全量分类匹配的性能损耗和匹配错误:
if(!laboratorioNombre) { listLaboratorioNombre.add(index.getLaboratorioNombre()); AssetCategory category = AssetCategoryLocalServiceUtil.addCategory( userId, groupId, index.getLaboratorioNombre(), Long.parseLong(_configuration.vocabularyId()), serviceContext); categoryId[0] = category.getCategoryId(); } else { // 已存在的情况再去查询匹配ID listCategories = AssetVocabularyLocalServiceUtil.getGroupVocabulary(groupId, vocabularyName).getCategories(); for(AssetCategory category : listCategories) { if(category.getName().equals(index.getLaboratorioNombre())) { categoryId[0] = category.getCategoryId(); break; } } }
内容的提问来源于stack exchange,提问作者Dimas Travieso
相关产品推荐
相关产品推荐

