Search code examples
liferayliferay-7

How to set a category to a Liferay Web Content in Java?


In Liferay 7, I have a Web Content, a vocabulary and a category.
How to set the category to the Web Content?

I wrote this code:

article = JournalArticleLocalServiceUtil.addArticle(...);
category = AssetCategoryLocalServiceUtil.addCategory(...);

AssetCategoryLocalServiceUtil.setAssetEntryAssetCategories(
    article.getPrimaryKey(), new long[]{category.getPrimaryKey()});

At execution no error, but the category does not show up on the edit page of the created Web Content:

enter image description here

The category has been created successfully, but the Web Content does not get that category assigned.

What am I doing wrong?

I have also tried addAssetEntryAssetCategories, addAssetEntryAssetCategory, addAssetCategoryAssetEntry: same problem.


Solution

  • Try using any of these 2 functions to add category:

    addAssetEntryAssetCategory(long entryId, long categoryId);
    addAssetEntryAssetCategories(long entryId, long[] categoryIds);
    

    In your code, you are using primary_key, however, as per documentation you should be using entry id and category id. So your function call should look like this:

    AssetEntry entry = AssetEntryLocalServiceUtil.fetchEntry(JournalArticle.class.getName(),  article.getResourcePrimKey());
    
    AssetCategoryLocalServiceUtil.addAssetEntryAssetCategory(
        entry.getEntryId(), category.getCategoryId());
    

    Since 7.0, they removed the getEntryId method from JournalArticle you would need an additional call to fetch it. There is a update method which you may also consider that would do this in single call. I'm still using 6.2 and catching up 7 :).

    Please note categories are designed for use by administrators, not regular users.