Thursday, March 8, 2012

Salesforce RecordType.sObjectType changes in managed packages

In hindsight this probably makes perfect sense but it did catch me out when working with an apex class used both within and outside a managed package.

I had a SOQL query against RecordType in the apex class that was used both in and out of a managed package. The query was filtering where the sObjectType equals a specific custom sObject (also in the managed package). The code worked fine outside the managed package but failed when deployed to a customers org.

The issue was the namespace prefix being prepended onto the custom sObjects name when used in the managed package.

E.g. Rather than filter on the custom sobject name directly:

List<RecordType> recordTypes = [Select r.SobjectType, r.Name, r.Id From RecordType r where sObjectType = 'SomeCustomObject__c'];

Use the schema meta data to get the correct value:

// In a managed package the SObjectType will be 'Prefix__SomeCustomObject__c' and in unmanaged it will just be 'SomeCustomObject__c'
Schema.DescribeSObjectResult someCustomObjectDescribe = SomeCustomObject__c.sObjectType.getDescribe();
string someCustomObjectSObjectType = someCustomObjectDescribe.getName();

List<RecordType> recordTypes = [Select r.SobjectType, r.Name, r.Id From RecordType r where sObjectType = :someCustomObjectSObjectType];