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
Sagar104Sagar104 

Assigining permission sets by apex trigger

Assigining permission sets by apex trigger
Requirement : There are some fields on the object , we need to grant permissions to edit  based on the picklist values.( i have written validations rules at first but didnt work)
Scenerio:I ve made all the fields of the object read only in Profile. then created permission set to the fields for edit permission. now based on the profile name I want to assign the same permission set to the user though the trigger.but it is not getting assigned. kindly assist what changes should be done?

Trigger Attached

trigger PSA_on_WO on Service_Order__c (before update)
    {
    if(Trigger.isBefore)
    {
      if(Trigger.isUpdate)
      {
          for ( Service_Order__c wo : trigger.new)
             {
                  id id1 = userinfo.getUserId();
                 id id2 = userinfo.getProfileId();
                String pf=[Select Id,Name from Profile where Id=:id2].Name;
              
              PermissionSetAssignment[] psa1 = new List<PermissionSetAssignment>();

              system.debug('profile ----> '+pf);
              system.debug('id1 ----> '+id1);
              system.debug('order status--->'+wo.Order_Status__c);
              system.debug('order type--->'+wo.Order_Type__c);
                  if(wo.Order_Status__c.equalsIgnoreCase('Draft') 
                           && wo.Order_Type__c.equalsIgnoreCase('FS'))
                 {
                       if(pf=='profile1' || pf == 'profile2' || pf=='profile3')
                    {
                         PermissionSetAssignment psa = new PermissionSetAssignment(PermissionSetId = '0PS3C0000004GLCWA2',AssigneeId = id1);
                 psa1.add(psa);        
                                   system.debug('permission set id----->' +psa.PermissionSetId);
                          system.debug('assignid id----->' +psa.AssigneeId);
                    }
                    else if(pf=='profile4')
                    {
                    PermissionSetAssignment psa = new PermissionSetAssignment(PermissionSetId = '0PS3C0000004GLW',AssigneeId = id1);
                     psa1.add(psa); 
                    }  
              
                   }
             insert psa1;
        }
    }
    }
}
Best Answer chosen by Sagar104
SalesFORCE_enFORCErSalesFORCE_enFORCEr
Instead of deleting it, I would recommend to do a check whether the Permission Set is already enabled for logged in user. If yes, then bypass the whole logic.

Please mark it BEST ANSWER if it solves the problem.

All Answers

SalesFORCE_enFORCErSalesFORCE_enFORCEr
This should work:
trigger PSA_on_WO on Service_Order__c (before update){
	List<PermissionSetAssignment> psa1 = new List<PermissionSetAssignment>();
	String pf=[Select Id,Name from Profile where Id=:UserInfo.getProfileId()].Name;
		for ( Service_Order__c wo : trigger.new){
                  if(wo.Order_Status__c.equalsIgnoreCase('Draft') && wo.Order_Type__c.equalsIgnoreCase('FS')){
                       if(pf=='profile1' || pf == 'profile2' || pf=='profile3'){
			PermissionSetAssignment psa = new PermissionSetAssignment(PermissionSetId = '0PS3C0000004GLCWA2',AssigneeId = UserInfo.getUserId());
			psa1.add(psa);        
			}
			else if(pf=='profile4')
			{
			PermissionSetAssignment psa = new PermissionSetAssignment(PermissionSetId = '0PS3C0000004GLW',AssigneeId = UserInfo.getUserId());
			psa1.add(psa); 
			}  
              
                   }
		}
	insert psa1;
}

 
Sagar104Sagar104
Hi,


it didnt work for me. its not assining permission set to the user, when i try to edit the record all the fields are read only,  and if i try to save the record getting below error:

Error: Invalid Data. 

Review all error messages below to correct your data.
Apex trigger PSA_on_WO caused an unexpected exception, contact your administrator: PSA_on_WO: execution of BeforeUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: 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: Service_Order__c: []: Trigger.PSA_on_WO: line 18, column 1


please help me with solution.
SalesFORCE_enFORCErSalesFORCE_enFORCEr
Move the whole logic in a future method and call that method from your trigger.
Sagar104Sagar104
still the permission set is not getting assigned and all the fields are in read only. please let me know what changes do i need to do ?


public class PSAclass 
{
 @future
  public static void assignPSA()
   {
     List<PermissionSetAssignment> psa1 = new List<PermissionSetAssignment>();
        String pf=[Select Id,Name from Profile where Id=:UserInfo.getProfileId()].Name;

    if(pf=='profile1' || pf == 'profile2' || pf=='profile3')
        {
            PermissionSetAssignment psa = new PermissionSetAssignment(PermissionSetId = '0PS3C0000004GLCWA2',AssigneeId = UserInfo.getUserId());
                psa1.add(psa); 
            
        }
        else if(pf=='profile4')
        {       
               PermissionSetAssignment psa = new PermissionSetAssignment(PermissionSetId = '0PS3C0000004GLW',AssigneeId = UserInfo.getUserId());
               psa1.add(psa); 
        }
    insert psa1;
   }
        
}

TRIGGER

trigger PSA_on_WO on Service_Order__c (before update)
{
    
    for ( Service_Order__c wo : trigger.new)
          {
               
               if(wo.Order_Status__c.equalsIgnoreCase('Draft') && wo.Order_Type__c.equalsIgnoreCase('FS'))
               {
                 PSAclass.assignPSA();
                   }
          }
}
Sagar104Sagar104
hey this is working . thanks alot..:-)
but my concern is here next time when i try to save the record , and in the debug log i am getting the below error
Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, Duplicate PermissionSetAssignment. Assignee: 005160000069Bez; Permission Set: 0PS3C0000004GLC: [AssigneeId, PermissionSetId]

can you please help me to delete the assigned permission set once the record is saved.
where do i need to do changes for deleting the assigned permission set once the record is being saved(trigger or class).?
how do i fetch the assigned permission set record to detele it?
SalesFORCE_enFORCErSalesFORCE_enFORCEr
Instead of deleting it, I would recommend to do a check whether the Permission Set is already enabled for logged in user. If yes, then bypass the whole logic.

Please mark it BEST ANSWER if it solves the problem.
This was selected as the best answer
Sagar104Sagar104
Thank you:-) can you please let me know how do i check whether the permission set is enabled or not. I have 8 permission set to assign depends on the field conditions(ex :Draft, Pending, Close). it will be great helpfull. I am stuck up with this issue from very long. 
Sagar104Sagar104
Hi sir, can you plz re open the case over here?