function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Chirag Sapkota 5Chirag Sapkota 5 

How to write a trigger to Auto Assign users who belong to one Permission sets to Chatter group

Hello All,
Wanting to write Apex Code (Both Class and Trigger) to auto assign Users who are assign to Permission Set (Test) to a Community Chatter group. 
I Manage to assign to a community chatter group based on Profile but not Based on Permission set. Could you please help?

Below is my code based on Profile. 
trigger User_trigger on User (after insert, before insert, after update, before update) {

    if ( Trigger.isInsert ) {   

        if ( Trigger.isAfter ) {

            List<id> UserIds = new List<id>();

            for ( user u: Trigger.new ) {

                if ( u.Profile.UserLicense.Name <> 'Customer Community Plus' ) {

                    UserIds.add(u.id);

                }                

            }

            if ( UserIds.size() > 0 ) {

                asyncApex.addUserToGroup(UserIds); 

            }          

        }

    }

global class AsyncApex {

    @future

    public static void AddUserToGroup(List<ID> UserIds) {

        try {

            List<CollaborationGroupMember> cgm = new List<CollaborationGroupMember>();                     

            Id cgID = [ Select Id

                        FROM CollaborationGroup

                        WHERE Name = 'All Clients Groups' LIMIT 1 ].ID;

           for ( Id UserId : UserIds ) {

               cgm.add(new CollaborationGroupMember (CollaborationGroupId = cgID, MemberId = UserId));  

           }

           insert cgm;

        } catch (QueryException qe) {

            System.debug('QueryException in AsyncApex.AddUserToGroup is :' + qe); 

        } catch (Exception ex) {

            System.debug('Exception in AsyncApex.AddUserToGroup is :' + ex);

        }   

    }

}