0

I am trying to assign permission set to all users of specific profile. While doing this i'm getting errors.Please help me to solve this.

Error: Line: 18, Column: 1 System.DmlException: Upsert failed. First exception on row 0; first error: DUPLICATE_VALUE, Duplicate PermissionSetAssignment. Assignee: 0052v00000eSqTK; Permission Set: 0PS2v000004upmS: [AssigneeId, PermissionSetId]

public class AssignPermissionSetToProfile {
@AuraEnabled
    public static void assignpermi(string profiles,string PermissionSett)
    {
        List<user> pro1=[select id,Profile.Name from user where Profile.Name=:profiles];
        
        PermissionSetAssignment permi2=[SELECT Id, PermissionSetId, PermissionSet.Name,PermissionSet.Profile.Name, 
                                        AssigneeId, Assignee.Name FROM PermissionSetAssignment where PermissionSet.Name=:PermissionSett limit 1];
        
        List<PermissionSetAssignment> permiList=new  List<PermissionSetAssignment>();
        
        for(user one:[SELECT Id,UserRole.Name,Profile.Name,IsActive FROM User WHERE Profile.Name =: profiles AND IsActive = true])
        {
            PermissionSetAssignment psa = new PermissionSetAssignment(PermissionSetId = permi2.PermissionSetId, AssigneeId = one.Id);
              permiList.add(psa);
              
        }
        upsert permiList;
    }
}
2
  • 1
    I'd guess that the permission set has already been assigned to a given user...? – Phil W Mar 29 at 14:06
  • Isn't this what permission set groups are for? – Caspar Harmer Mar 29 at 17:50
0

Got solution for it

public class AssignPermissionSetToProfile {
@AuraEnabled
    public static void assignpermi(string profiles,string Sett)
    {
        PermissionSet permii=[select id from PermissionSet where Name=:Sett];
        List<PermissionSetAssignment> permiList=new  List<PermissionSetAssignment>();
        List<PermissionSetAssignment> userinfo=[SELECT AssigneeId FROM PermissionSetAssignment WHERE PermissionSet.Name =:Sett];
        set<Id> userId=new set<Id>();
        for(PermissionSetAssignment dd:userinfo)
        {
            userId.add(dd.AssigneeId);
        }
        for(user one:[SELECT Id,UserRole.Name,Profile.Name,IsActive FROM User WHERE Profile.Name =: profiles ])
        {
            if(userId.contains(one.Id))
            {
                system.debug('Already added user');
            }
            else
            {
            PermissionSetAssignment psa = new PermissionSetAssignment(PermissionSetId = permii.id, AssigneeId = one.Id);
            permiList.add(psa);
            }
        }
        upsert permiList;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.