I have created an "After Trigger" to automatically assign/remove a permission set to a user. The trigger works fine, but from what I understand, line 15 of my code is not best practice:
PermissionSetId = tcrmAssignment[0].PermissionSetId;
What the trigger does is anytime a user is created or activated, a permission is automatically assigned to the user. When a user is inactive, the permission is removed.
I first did this requirement using Flow builder. But for some reasons the Flow builder does not work for 2 other System Admin users even though their profiles have the exact same parameters (meaning Flow User checked on their profile, as well as all the appropriate permissions and rights as mine and the rest of Admins), but for the other 3 System Admin including myself the Flow Builder works.
That's the reason I took the trigger route, which is not my preferred choice.
As I said: The code works fine, but I read somewhere that we should not assign an Id to a record in this manner:
PermissionSetId = tcrmAssignment[0].PermissionSetId;
Could someone help reviewing my code to see, if it has been correctly written?
Please see below the Handler class. Thanks!
public class TCRMPermissionSetAssignmentHandler {
public static void addTCRMPermissionSetAssignment(List<User> userList) {
List<PermissionSetAssignment> tcrmPermAssignmentList = new List<PermissionSetAssignment>();
List<PermissionSetAssignment> tcrmAssignment = new List<PermissionSetAssignment>();
for(PermissionSetAssignment perm : [SELECT PermissionSetId, AssigneeId FROM PermissionSetAssignment WHERE PermissionSet.Name = 'EinsteinAnalyticsUser']) {
tcrmAssignment.add(perm);
}
update tcrmAssignment;
for(User newUser : userList) {
if(newUser.IsActive == true) {
tcrmPermAssignmentList.add(new PermissionSetAssignment(AssigneeId = newUser.Id,
PermissionSetId = tcrmAssignment[0].PermissionSetId));
}
}
insert tcrmPermAssignmentList;
}
public static void removeTCRMPermissionSetAssignment(List<User> userList) {
Set<Id> userIds = new Set<Id>();
for(User u : userList) {
if(u.IsActive == false) userIds.add(u.Id);
}
List<PermissionSetAssignment> tcrmAssignmentList = [SELECT Id, AssigneeId, PermissionSetId FROM PermissionSetAssignment
WHERE AssigneeId = :userIds AND PermissionSetId IN
(SELECT Id FROM PermissionSet WHERE IsOwnedByProfile = false)];
delete tcrmAssignmentList;
}
}