2

Our managed package has a namespace, say DemoApp, and a custom object named Form__c,

the client's org also has a custom object Form__c

According to the doc here: https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_type.htm

To get the name of a local type, set the namespace argument to an empty string or null. For example, Type t = Type.forName('', 'ClassName');.

but when executing Type.forName('', 'Form__c') in the package, we get DemoApp__Form__c instead of the Form__c, why is that?

How can we get the local object in the managed package?

1
  • Type.forName('Schema', objectAPIName) does not work but Schema.getGlobalDescribe does.
    – Adam
    Commented Jun 4, 2021 at 6:30

2 Answers 2

2

I assume that you are executing Type.forName in your managed package code. In this context many of the Salesforce APIs operate as if a namespace isn't defined, and this allows all your managed package code to reference stuff within itself (objects, fields, classes etc.) without need of the namespace prefix. This is the reason you see what you see.

Local objects with the same base name as packaged objects are always troublesome, and for me the rule of thumb is to avoid it. However, you can work around the discovery issue in various ways. One option is to use Schema.getGlobalDescribe and use a direct access using the full name as the key value into that map; as the documentation says:

The keys are prefixed with the namespace, if any.

Just make sure this code is using a recent API version (again the documentation helps you out here).

I would not normally suggest using Schema.getGlobalDescribe because (at least historically) its performance sucks. Make sure you minimize the usages in your code. Take a look at this Q&A for more.

An alternative is to see if Type.forName('Schema', objectAPIName) works for you, though I suspect it might not.

By the way, much of the code you posted is quite unnecessary and overcomplex; the Schema gives you tools for examining various facets of a given object type quite straight forwardly.

1

We found another way to describe local objects in the managed package.

String localObjectName = 'Form__c';

String sObjectJson = '{"attributes":{"type":"' + localObjectName + '"}}';

SObject localSObject = (SObject) JSON.deserialize(sObjectJson, SObject.class);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .