• Emanuela Cipriano
  • NEWBIE
  • 0 Points
  • Member since 2021

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
Hi Experts,

I have requirement to write a trigger on user object. Whenever a user is created or updated based on the profile, I need to assign the permission set. I have created 2 custom object for this: Profile__c (master) and Permission_Set__c(detail). In Profile I have Saved a record name__c: "Standard Employee" and Id__c="15 digit Id " of real profile & same way I have created 3 records in Permission Set with name__c with original name of Permission Set and Id__c for its child record.  I have to do this using custom object because we have around 124 permission Set which will continued to be added.

Trigger :
trigger permissionSetAssignment on User(after insert, after update){
    if(trigger.IsAfter && trigger.IsInsert){
        PermissionSetAssignment_Handler.afterInsert(Trigger.new);
    }
    if(trigger.IsAfter && trigger.IsUpdate){
        PermissionSetAssignment_Handler.afterUpdate(Trigger.oldMap,Trigger.new);
    }
}

Handler Class for Update:

public class PermissionSetAssignment_Handler {
    public static void afterInsert(List<User> users){
     /* Logic Yet to be written*/      
    }
    public static void afterUpdate(Map<Id,User> oldUsers, List<User> newUsers){
        Set<Id> userIds = new Set<Id>();
        Map<Id,User> userPerm = new Map<Id,User>();
        List<PermissionSetAssignment> insertList = new List<PermissionSetAssignment>();
        for(User u:newUsers){
            User checkUser = oldUsers.get(u.ID);
            if(u.ProfileId != checkUser.ProfileId){
                userIds.add(u.Id);
            }
        }
        List<PermissionSetAssignment> psa = [Select Id from PermissionSetAssignment where assigneeId in:userIds and permissionSetId in (Select Id from PermissionSet where IsOwnedByProfile=False)];
        delete psa;
        List<Profile__c> profiles = [SELECT Id,Id__c,name,(Select Id,Id__c,name from Permission_Sets__r) FROM Profile__c];
        List<Permission_Set__c> permissionSets = [Select Id,Id__c from Permission_Set__c];
        for(User u:newUsers){
            for(Profile__c pc:profiles){
 /* Here I am stucked I want to fetch only those permissionSets which are under under profile but with below code I'll end up adding all permission Sets */               
                if(u.ProfileId == pc.Id__c){                   
                    for(permission_Set__c ps:permissionSets){
                    PermissionSetAssignment sep = new PermissionSetAssignment();
                    sep.AssigneeId=u.id;
                    sep.PermissionSetId=ps.Id__c;
                    insertList.add(sep);
                    }
                }
            } 
    }
            insert  insertList;        
}
}