[SalesForce] Accessing Custom Labels through Batch Apex

We have a mobile application which needs custom labels for different languages through Salesforce custom labels.

Because of API limit on metadata api, we are planning to store all the required custom labels in a "Custom Object". So, instead of querying metadata API to get the list of custom labels, a mobile device will query this custom object to get all required custom labels. It will save number of APIs.

We tried to write a batch process, which will sync all the custom labels values into the custom object using the metadata API. We are currently making use of the MetadataService as mentioned below :

 MetadataService.MetadataPort service = new MetadataService.MetadataPort();
   service.SessionHeader = new MetadataService.SessionHeader_element();
   service.SessionHeader.sessionId = UserInfo.getSessionId();
 List<MetadataService.ListMetadataQuery> queriesList = new List<MetadataService.ListMetadataQuery>(); 

From above code, we are getting NULL value for "UserInfo.getSessionId()". When we pass the session id as a parameter to batch constructor, we are getting the session value but it throws "Invalid Session ID" error.

Couple of questions come to my mind for the above problem:

  1. How do we pass a valid user session id to batch apex?
  2. Can we directly access the "customlabels.labels" file through apex code, which is available under "src / labels / CustomLabels.labels" in Eclipse source.
  3. Is there any alternate approach to transfer the Custom Labels values to external applications?

Thanks in Advance.

Regards,

Ashish Shukla

Best Answer

@Ashish: Alternately, you should be able to create a Visualforce page which will emit JSON data. Within page you can place all labels and merge fields to emit label values (in logged-in user's language). This can also avoid creating a different custom setting/ object to store values and fully leverage usage of Custom labels for translated values.

Something like:- VF Page:-

{
   "Invoice" : "{!$Label.Invoice}",
   "PurchaseOrder" : "{!$Label.PurchaseOrder}"
}

Accessing this web page via mobile app (as a REST API) should not be an issue.