RE: Liferay 7.2 - How to set portlets to div programmatically

Fabio Carvalho, modified 6 Years ago. Junior Member Posts: 81 Join Date: 6/25/19 Recent Posts
Hi,

I am using a custom template for my layout. My custom_template.tpl has a <div id="something" />. My question is: if I having the div ID and portlet ID, how do I programmatically add a portlet to this div?
thumbnail
David H Nebinger, modified 6 Years ago. Liferay Legend Posts: 14933 Join Date: 9/2/06 Recent Posts
Normally you would just embed the portlet right in the layout template itself. You wouldn't want to be dynamically trying to add/remove portlets in a layout template during page aggregation time.
thumbnail
Olaf Kock, modified 6 Years ago. Liferay Legend Posts: 6441 Join Date: 9/23/08 Recent Posts
Feels like a X-Y problem to me. What is the reason for trying this? This is the kind of infrastructural work that you shouldn't worry about in an environment like Liferay. Rather concentrate on solving business problems than infrastructure.
There's a small fraction of problems where this might be feasible, but most of the questions ("how do I do X (because I've been asked to Y)") end up not justifying ignoring the existing infrastructure.
One more argument: You might solve the problem now, but you'll have to maintain it in future upgrades.
Fabio Carvalho, modified 6 Years ago. Junior Member Posts: 81 Join Date: 6/25/19 Recent Posts
Hi David and Olaf,

I have a JSON file with an array of Layouts. Each Layout have a name, url, template and portlets IDs to add according to his template. Here is an example of an object of this array:
 {
&nbsp; &nbsp; "name": "Home",
&nbsp; &nbsp; "url": "home",
&nbsp; &nbsp; "layout": "my_custom_template",
&nbsp; &nbsp; "portlets": [
&nbsp; &nbsp; &nbsp; &nbsp; {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "column": "column-1",
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "portlet": "com_liferay_portal_search_web_search_bar_portlet_SearchBarPortlet"
&nbsp; &nbsp; &nbsp; &nbsp; },
&nbsp; &nbsp; &nbsp; &nbsp; {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "column": "column-2",
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "portlet": "com_liferay_portal_search_web_search_bar_portlet_SearchBarPortlet"
&nbsp; &nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; ]
}


I ended up with something like this:
LayoutTypePortlet type = (LayoutTypePortlet) layout.getLayoutType();
type.addPortletId(theme.getUserId(), myPortletId, myColumnId, -1, false);

It is producing what I want. Is there any consequence of doing things like this?