RE: Liferay 7.2 - How to add groups programmatically?

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

I am trying to add groups and layouts programmatically in my custom portlet. Right now I am successfully adding layouts like this:
public void addLayout(ActionRequest request, ActionResponse response) throws IOException, PortletException, PortalException {
    ThemeDisplay theme = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
        
    long userId = theme.getUserId();
    long groupId = theme.getSiteGroupId();
    String name = ParamUtil.getString(request, "name");
        
    LayoutLocalServiceUtil.addLayout(
        userId, 
        groupId, 
        false, 
        0, 
        name, 
        null, 
        null, 
        LayoutConstants.TYPE_PORTLET, 
        false, 
        null, 
        new ServiceContext()
​​​​​​​    );
}

But I can't seem to find a good example for the groups. I am confused with some parameters from the GroupLocalServiceUtil.addGroup() method. Is there are any good example of how to add groups programmatically?

Thank you!
thumbnail
Christoph Rabel, modified 6 Years ago. Liferay Legend Posts: 1555 Join Date: 9/24/09 Recent Posts
What kind of groups?
The term  group is a bit ambiguous in Liferay. Do you want to add Usergroups or do you want to add sites/organisations?
Fabio Carvalho, modified 6 Years ago. Junior Member Posts: 81 Join Date: 6/25/19 Recent Posts
Hi Christoph,

After some debugging I found what could be the correct way to create a group programmatically. My method is the following:
public void addGroup(ActionRequest request, ActionResponse response) throws IOException, PortletException, PortalException {
    ThemeDisplay theme = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);    long userId = theme.getUserId();
    String name = ParamUtil.getString(request, "name");
        
&nbsp; &nbsp; Map<locale, string> nameMap = new HashMap<locale, string>();
&nbsp; &nbsp; nameMap.put(LocaleUtil.US, name);
&nbsp; &nbsp; nameMap.put(LocaleUtil.PORTUGAL, name);
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;
&nbsp; &nbsp; GroupLocalServiceUtil.addGroup(
&nbsp; &nbsp; &nbsp; &nbsp; userId,&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; GroupConstants.DEFAULT_PARENT_GROUP_ID,&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; null,&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; 0,&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; GroupConstants.DEFAULT_LIVE_GROUP_ID,&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; nameMap,&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; null,&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; GroupConstants.TYPE_SITE_OPEN,
&nbsp; &nbsp; &nbsp; &nbsp; false,&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; GroupConstants.DEFAULT_MEMBERSHIP_RESTRICTION,&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; null,&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; true,&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; true,&nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; new ServiceContext()
&nbsp; &nbsp; );
}</locale,></locale,>

I think this is creating a site/organization if I am not mistaken.