Monday, 16 July 2018


Trigger for Adding and removing User to Permission set based on User roles


trigger AssignPermissionSet on User (after insert,after Update) {
    PermissionSet pereset = [SELECT Id FROM PermissionSet WHERE Label ='SBU Impact Visible'];
    Set<ID> addIds = new Set<Id>(),
            removeIds = new Set<Id>(),
            roleIds = new Map<Id, UserRole>([
        SELECT  Id FROM UserRole
        WHERE   Name LIKE '%E&C%' OR Name LIKE '%Commerical Ops%' OR Name LIKE '%Energy & Chemicals%' OR Name LIKE '%All Fluor%'
    ]).keySet();
    for(User record: Trigger.new) {
        (record.IsActive && roleIds.contains(record.UserRoleId)? addIds: removeIds).add(record.Id);
    }
   
    PermissionSetAssignment[] permissionSetList = new PermissionSetAssignment[0];
    addIds.removeAll(new Map<Id, AggregateResult>([SELECT AssigneeId Id FROM PermissionSetAssignment
       WHERE AssigneeId = :addIds AND PermissionSetId = :pereset.Id GROUP BY AssigneeId]).keySet());
   
    for(Id userId: addIds) {
        permissionSetList.add(new PermissionSetAssignment(PermissionSetId = pereset.id, AssigneeId = userId));
    }
    upsert permissionSetList;
    delete [SELECT Id FROM PermissionSetAssignment WHERE AssigneeId = :removeIds AND PermissionSetId = :pereset.Id];
}