Merging Layouts together

One of the common requirements that I have encountered is to Merge Layouts. Like people want on login all their community Layouts are shown along with the guest Layouts.
Or they want user layouts + org layouts together.

In this tutorial i would show how this can be achieved.

First Thought
  • How does all my Layouts get displayed as tabs in navigation?
  • How does it by default show the Home page as selected or the first tab as selected?
I found on debugging that above mentioned logic is written in ServicePreAction class. Here all the layouts that are to be displayed on a page as tabs are stored in themeDisplay along with one selected layout.

Where did I modify

I had to modify VelocityVariables in extension to merge my Layouts. Here you have a method named insertVariables where themeDisplay is inserted. Now the catch is
to manipulate on this themeDisplay object and set its Layouts and default layouts as we require.
This i had done using Extension environment.

  • In extension environment make a java file at the same package structure and name as of VelocityVariables
  • Find its insertVariables method
  • Find this line if (themeDisplay != null) {
  • Below that add your custom code to set its Layout. Like add this line below that
layouts = getLayouts(themeDisplay)
  • Now create a method that does the merging logic as under. Assuming that by default when user logs in he sees his Guest community pages and the requirement is to show users public pages along with that
private static List getLayouts(ThemeDisplay themeDisplay){
List layouts = themeDisplay.getLayouts;
return layouts;
  • The above piece of code will do nothing but what is happening already like showing the current layouts. Now we have to write our code in between the two lines such that the returning list of Layouts has our user layouts as well. So first we need user layouts. This can be achieved with following snippet
Group userGroup = themeDisplay.getUser().getGroup();
List userLayouts = LayoutLocalServiceUtil.getLayouts(userGroup.getGroupId(), false,LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
  • This will retrieve all the user layouts. Make sure this happens when user is logged in otherwise it may give exception since there is no user to retrieve their layouts. This can be achieved by wrapping the above snippet in a if condition which checks themeDisplay.isSignedIn().
  • The next step is pretty simple. You have to merge both layouts and return the same.
  • Hope that helps some. This may not be the ideal solution, if you have better solution please do share.

1 comment: