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
soorya rsoorya r 

Create permission set by apex class, "Internal Salesforce.com error"

HI All,

I am getting "Internal salesforce.com error" when creating permission set through apex class. Actually I am deleting the existing permission set and create a new permission set with that same name. If the existing permissions set does't have Permission set Assignments then its works fine or  it shows the above error and it is not executed. Please give me suggestion.

Thanks. 
NagendraNagendra (Salesforce Developers) 
Hi Soorya,

Sorry for this issue you are encountering.

Please try the below code which works fine for me.

Apex Class:
global class AssignPermissionSet {

  @future 
  static void AssignPermissionSetToUsers (Set<Id> usersId) {
    // Perform long-running code
	List<PermissionSetAssignment> permissionSetList = new List<PermissionSetAssignment>();
	for (User u : [Select Id, Name FROM User Where Id IN : usersId]){ // Add fields as per your requirement...
		PermissionSetAssignment psa = new PermissionSetAssignment (PermissionSetId = 'XXXXXXXXXXXc94', AssigneeId = u.Id);
		permissionSetList.add(psa);
	}
	upsert permissionSetList;
  }
}
Apex Trigger:
trigger AssignPermissionSet on Contact (after Update){
Set<ID> usersId = new Set<Id>();
Set<Id> contactIdsSet = new Set<Id>();
for (contact c :trigger.new) {
    if(c.Is_SUper_User__c == true) {
       contactIdsSet.add(c.Id);
    }
}
For(User usr : [Select Id, Name, From User Where ContactId!=null AND ContactId IN : contactIdsSet]){
	usersId.add(usr.Id);
}
  AssignPermissionSet.AssignPermissionSetToUsers(usersId);
}
Hope this helps.

Regards,
Nagendra