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
Apoorva SharmaApoorva Sharma 

MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): PermissionSetAssignment, original object: Account:

Hii all
I am trying to asssign a user dynamically  to a permission set but got mixed dml exception. Here is my code:

Public class PermissionSetAccess{

   public static void execute(Id id,List<SObject> scope) {

        List<PermissionSetAssignment> newPermissionSetAccess = new List<PermissionSetAssignment>(); //list for new permission sets
        Set<String> usersWithAccess = new Set<String>(); //set for users Ids with access to the permission set already
        Id psaId; //Id of the permission set we want Users to be assigned

        //query for the permission set Id
        for (PermissionSet ps : [SELECT Id FROM PermissionSet WHERE Name = 'Approver']) {
        system.debug('in ps query');
            psaId = ps.Id; //assign the premission set Id
            for (PermissionSetAssignment psa : [SELECT AssigneeId FROM PermissionSetAssignment WHERE PermissionSetId = :ps.Id]) { //query for the permission set Users that are already assigned
                usersWithAccess.add(psa.AssigneeId); //add the Id of each assigned User to our set
                system.debug('usersWithAccess.add(psa.AssigneeId)'+usersWithAccess);
            }
        }

        //compare the list of all users to the list of already granted users and make another list of those missing access
        //take that list of missing access and grant access
        for (SObject s : scope) { //for all objects from our batch
            //User u = (User)s; //grab the individual User record
            
            if (!usersWithAccess.contains(id)) { //if the User is not in our 'already has access' set
                PermissionSetAssignment newPSA = new PermissionSetAssignment(); //PermissionSetAssignment sobject
                newPSA.PermissionSetId = psaId; //set the permission set Id
                newPSA.AssigneeId = id; //set the User Id
                newPermissionSetAccess.add(newPSA); //add the record to our list
            }
        }
        if (!newPermissionSetAccess.isEmpty()) { //if there are records to insert
            insert newPermissionSetAccess; //insert
             system.debug('sucess');
        }
    }

}

i am calling it in a triggerr
Best Answer chosen by Apoorva Sharma
BalajiRanganathanBalajiRanganathan
try to use @future for this execute method(but you have to update it as you can not pass Sobject for futuremethod)

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dml_non_mix_sobjects.htm