2

Salesforce documentation has Dynamic Sobject Creation Example The test class gives an example of how to check if object exists and the create the object. Unfortunately they use Account which every org has. How do you do the same thing with CustomObject__c c? Not Sobject s which I know we can use but requires get and put which is bit more cumbersome vs c.Name.

If I use CustomObject__c = (CustomObject__c)DynamicSobjectCreation.createObject(typeName) and it doesn't exist in the org, get a deployment error in SFDX.

Invalid type: CustomObject__c

The point of the exercise is to see if the object exists in the first place and instantiate it.

    // Create a new sObject by passing the sObject type as an argument.
    **Account a = (Account)DynamicSObjectCreation.createObject(typeName);**        
    System.assertEquals(typeName, String.valueOf(a.getSobjectType()));
    // Set the account name and insert the account.
    a.Name = acctName;
    insert a;
}

}

1 Answer 1

3

UPDATE 2:

You can't create an SObject in Apex if it doesn't exist in the system, because Salesforce doesn't know what fields etc. you want.

If you want to check if object exists in the org you can do the following

public static Boolean isSObjectExists(String sobjectName) {
    return Schema.getGlobalDescribe().containsKey(sobjectName);
}

just use GlobalSchema.

If you are not sure about SObject itself and want to work with it then use the following.

String sobjectName;
SObject obj = Schema.getGlobalDescribe().get(sobjectName).newSObject();

// obj.get('field');
// obj.put('field', 'value');
// obj.getSObjectType() == Schema.getGlobalDescribe().get(sobjectName).getDescribe().getSObjectType()

UPDATE:

here is the better performance option as per Adrian suggestion using Type.

public static Boolean isSObjectExists(String sobjectName) {
    return Type.forName('Schema', sobjectName) != null;
}

also dynamic creation

String sobjectName = 'Account';
SObject obj = (SObject) Type.forName('Schema', sobjectName).newInstance();

// obj.get('field');
// obj.put('field', 'value');
// obj.getSObjectType() == Schema.getGlobalDescribe().get(sobjectName).getDescribe().getSObjectType()

12
  • 1
    This approach is significantly slower than just Type.forName(sObjectName) != null.
    – Adrian Larson
    Aug 17, 2021 at 20:32
  • true, thanks. To be honest didn't know Type.forName was working on SObject
    – ytiq
    Aug 17, 2021 at 20:33
  • 1
    You can also create classes with names like Account, then probably better to use Schema.Account
    – ytiq
    Aug 17, 2021 at 20:37
  • 1
    I recommend switching the order, since global describe is really expensive to call.
    – Phil W
    Aug 17, 2021 at 21:14
  • 2
    It should be Type.forName('Schema',sobjectName). This avoids any potential shadowing.
    – sfdcfox
    Aug 17, 2021 at 21:43

You must log in to answer this question.

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