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
Olesja SandibaOlesja Sandiba 

Exclude some profiles from method in Apex Class

Hello everyone, I have a question connected with exclusion of some profiles from method in Apex Class.
I have a method in CaseManagment class, which prevent closure of Case when case have email drafts. But, for some purposes this function have to work for all profiles except "Sales Manager" ,  "Sales Backoffice" profiles. How can i exclude this profiles from function?


         Id StandardRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('Case_Standard').getRecordTypeId();
            
        Map<String,Boolean> emailMessageMap = new Map<String,Boolean>();
        List<Case> closedCasesList = new List<Case>();
        
        for(Case c : newMap.values()){
            if(c.RecordTypeId == StandardRecordTypeId){
            
            if (c.Status != oldMap.get(c.Id).Status && c.Status == 'Closed'){
                closedCasesList.add(c);
                }
            }
        }
        
        List<EmailMessage> emailMessageList = [SELECT ID,Status,RelatedToId FROM EmailMessage WHERE RelatedToId IN:closedCasesList AND Status='5'];
         System.debug(emailMessageList.size());
        for(EmailMessage em : emailMessageList){
            emailMessageMap.put(em.RelatedToId,true);
            
        }
            
        for(Case c : closedCasesList){
            
            if (emailMessageMap.get(c.Id)!=null){
                  
                c.addError('Email Draft exist');
            }
        }        
        
    }

I have a method that identify current user profile, but how it use in this case? 

Id currentProfile=userinfo.getProfileId();
        
       Profile profileName=[Select Name from Profile where Id=:currentProfile];
        System.debug(profileName.Name);

Thanks in advance!

Andrew GAndrew G
you are on the right path.  
Basically, get the Ids for those profiles that are not allowed to edit the record.
Then do a list.contains()
 
List<Profile> profiles = [SELECT Id FROM Profile WHERE Name LIKE 'Sale%'];
List<String> profileIds = new List<String>();
for (Profile p : profiles){
    profileIds.add(p.Id);
}

if(profileIds.contains(userinfo.getProfileId())) {
    System.debug('FOUND');
   //do some sort of escape
} else {
  //do your code process
}

you could probably do something similar with SELECTing a Map and then do a map.containsKey();
Map<Profile> profilesMap = [SELECT Id FROM Profile WHERE Name LIKE 'Sale%'];

if(profileIdsMap.containsKey(userinfo.getProfileId())) {
    System.debug('FOUND');
   //do some sort of escape
} else {
  //do your code process
}

regards
Andrew​​​​​​​