Background
I'm using Apex Wrapper Salesforce Metadata API to update some picklist values on the fly. (i.e. Every time a record is inserted/updated/deleted in Table A, I'm adding/subtracting picklist values into a MultiselectePicklist in table B).
Since,
An Apex trigger can execute a callout when the callout is invoked within a method defined as asynchronous: that is, defined with the @future keyword.
I implemented a method with the future annotation, and
For Apex code that is executed asynchronously, such as @future methods, Batch Apex jobs, or scheduled Apex jobs, getSessionId returns null.
so, I needed to pass the session Id as a parameter in the method, I implemented something like:
@future (callout=true)
public static void addContactPicklistPreference(List<String> preferences, String sessionId){
Schema.DescribeSObjectResult sObjectDescribe = Contact.sObjectType.getDescribe();
String picklistFieldName = 'Preference__c';
Picklist_MDT.addPicklistValues(sObjectDescribe, picklistFieldName, artists, sessionId);
}
public class Picklist_MDT {
public static void addPicklistValues(Schema.DescribeSObjectResult sObjectDescribe, String picklistFieldName, List<String> picklistValueNames, String sessionId) {
MetadataService.MetadataPort service = createService(sessionId);
...
}
public static MetadataService.MetadataPort createService(String sessionId) {
MetadataService.MetadataPort service = new MetadataService.MetadataPort();
service.SessionHeader = new MetadataService.SessionHeader_element();
service.SessionHeader.sessionId = sessionId;
return service;
}
}
And called the addContactPicklistPreference
method from trigger context passing it the UserInfo.getSessionId()
value.
Problem
This worked just fine in salesforce classic but not in lightning, when it triggers in lightning I'm getting System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: INVALID_SESSION_ID...
. Funny thing is that if I put a System.debug(UserInfo.getSessionId());
before calling the addContactPicklistPreference
method it prints a valid session Id in both classic and lightning.
I would really appreciate any input about this.