ADT Template - fetch DDMTemplate by name

Problem: sometimes you may need to access DDMTemplate in the asset publisher template, you know it’s name and you need to fetch it by name, but, unfortunately, there is no such service for that - you can fetch it only by templateKey:


public DDMTemplate getTemplate(long groupId, long classNameId, String templateKey)


 As templateKey is generated automatically - it’s not a good idea to hard-code it directly in ADT.


Solution: here is an FTL function, which finds the required DDMTemplate in Global scope using the template name:


<#function getDDMTemplateByName templateName>
   <#assign ddmTemplateLocalService = serviceLocator.findService("com.liferay.dynamic.data.mapping.service.DDMTemplateLocalService") />
   <#assign companyLocalService = serviceLocator.findService("com.liferay.portal.kernel.service.CompanyLocalService")/>
   <#assign portalUtil = staticUtil["com.liferay.portal.kernel.util.PortalUtil"] />
   <#assign company = portalUtil.getCompany(request) />
   <#assign companyGroup = company.getGroup() />
   <#assign globalGroupId = companyGroup.getGroupId() />
   <#assign ddmTemplates = ddmTemplateLocalService.getTemplatesByGroupId(globalGroupId) />
   <#assign ddmTemplate = "" />
   <#list ddmTemplates as curTemplate>
       <#if curTemplate.getNameCurrentValue() == templateName>
           <#assign ddmTemplate = curTemplate />
       </#if>
   </#list>
   <#return ddmTemplate>
</#function>

You may declare this function in your ADT template, and then use it, like this:


<#assign ddmTemplate = getDDMTemplateByName("NEWS_TEMPLATE") />

After this you may use the ddmTemplate object  - for example, for rendering a web content.

P.S. make sure, you have enabled staticUtil and serviceLocator variables, see:
https://lifedev-solutions.blogspot.com/2019/09/fixing-missing-variables-in-adt.html

Comments

Popular posts from this blog

Liferay Search Container Example

Liferay DXP - max upload file size

Liferay Keycloak integration