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 and class

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 and class.
now it is working but when i edit the record for the first time permission set not being assigned, when i re edit the same record for the 2nd time , then permission set is getting assigned. please let me know what is the issue here.

CLASS

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();
                   }
          }
}