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
Vikas Kumar 135Vikas Kumar 135 

Error while upserting PermissionSet using Apex

Hi All,

I am getting this below error while upserting the permission set to the user object. I would appreciate someone can provide me with the correct solution. The requirement is to give one common permission to both the users.

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger Addpermission caused an unexpected exception, contact your administrator: Addpermission: execution of AfterUpdate caused by: System.DmlException: Upsert failed. First exception on row 0; first error: DUPLICATE_VALUE, Duplicate PermissionSetAssignment. Assignee: 00546000000aUk8; Permission Set: 0PS46000000IhId: [AssigneeId, PermissionSetId]: Class.userHandler.addPermission: line 44, column 1

Below is the class

Public class userHandler{

Public static void addPermission(List<user>newUser) 
    {
    
    List<PermissionSetAssignment> permissionSetList = new List<PermissionSetAssignment>();
    List<User> userList= [SELECT ID,UserRole.Name,Profile.Name,IsActive FROM User WHERE Profile.Name = 'Solution Manager' or Profile.Name='Marketing User' ];
    for (User u : userList)
    { 
       if(u.Profile.Name=='Solution Manager')
       {
        system.debug(u);
        PermissionSetAssignment psa1 = new PermissionSetAssignment (PermissionSetId = Label.Test, AssigneeId = u.Id);
        permissionSetList.add(psa1);
        PermissionSetAssignment psa2 =new PermissionSetAssignment (PermissionSetId = Label.CRM_Permission_Set, AssigneeId = u.Id);
        permissionSetList.add(psa2);
        }
        
        Else if(u.Profile.Name=='Marketing User')
       {
        system.debug(u);
        PermissionSetAssignment psa3 = new PermissionSetAssignment (PermissionSetId = Label.Test, AssigneeId = u.Id);
        permissionSetList.add(psa3);
        PermissionSetAssignment psa4 =new PermissionSetAssignment (PermissionSetId = Label.Service_Cloud_User, AssigneeId = u.Id);
        permissionSetList.add(psa4);
        }
   
    }
    
  Boolean isinsertfirstTime = true;
  try{  
      upsert permissionSetList;
     }catch (DMLException e) 
     {
     system.debug('exception caught' + e);
     if(isinsertfirstTime)
      {
       upsert permissionSetList;
      }
     }
 }
}
Jay GuruswamyJay Guruswamy
Hi,

The error messages says that you are trying to assign the same permission to same user more than once.

Hence run a query first on the PermissionSetAssignment Object

Select p.PermissionSetId, p.AssigneeId From PermissionSetAssignment p

and then check, whether there is already a match there in the above list before assigning.