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:
- Retrieve this category ID.
- Use it to fetch the corresponding category name.
- 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
- Fetching the
category
Parameter:- The category ID is retrieved from the request parameter.
request.getParameter("category")
checks if the parameter exists and assigns its value tocategoryId
.
- Using the Service Locator:
serviceLocator.findService("com.liferay.asset.kernel.service.AssetCategoryLocalService")
provides access to theAssetCategoryLocalService
class.
- Fetching the Category Object:
categoryService.getAssetCategory(categoryId?number)
fetches theAssetCategory
object corresponding to the provided ID.
- Displaying the Category Name:
${category.getTitle(locale)}
retrieves the localized title of the category.- If the category ID is invalid or not found, a fallback message is displayed.
Troubleshooting Tips
serviceLocator
Restriction:- Ensure
serviceLocator
is not restricted in Control Panel > System Settings > Template Engines > FreeMarker. - If restricted, remove it from the “Restricted Variables” list.
- Ensure
- Invalid Service Path:
- Verify the correct service path:
com.liferay.asset.kernel.service.AssetCategoryLocalService
.
- Verify the correct service path:
- Reindex Categories:
- If categories are not found, reindex them through Control Panel > Search > Index Actions > Execute Reindex All Indexes.
Also Read: How can I embed a widget in another widget template in Liferay?