How to Fetch a Category Name Using Category ID in Liferay with FreeMarker

Author: Ajay Choudhary

Liferay Version: 7.1, 7.2, 7.3, 7.4

In Liferay, categories help organize and classify content, making it easier to manage and retrieve. Often, you might have a category ID and want to fetch its name dynamically in a FreeMarker template. In this guide, we’ll walk you through the steps to achieve this using Liferay’s service locator.

Understanding the Scenario

Let’s say you have a category parameter in the request URL, which represents a category ID. You want to:

  1. Retrieve this category ID.
  2. Use it to fetch the corresponding category name.
  3. Display the category name in the template.

Steps to Implement

Here’s the complete FreeMarker code snippet for achieving this:

<#assign categoryId = ""> 

<#if request.getParameter("category")?has_content> 
    <#assign categoryId = request.getParameter("category")> 
</#if> 

<#if categoryId?has_content> 
    <#-- Use service locator to get AssetCategoryLocalService --> 
    <#assign categoryService = serviceLocator.findService("com.liferay.asset.kernel.service.AssetCategoryLocalService")> 
    
    <#-- Get the AssetCategory object --> 
    <#assign category = categoryService.getAssetCategory(categoryId?number)> 
    
    <#if category??> 
        Category Name: ${category.getTitle(locale)} 
    <#else> 
        Category not found with ID: ${categoryId} 
    </#if> 
</#if>

Code Breakdown

Troubleshooting Tips

Also Read: How can I embed a widget in another widget template in Liferay?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

close
Thanks !

Thanks for sharing this, you are awesome !