0

I have a list of sobject and I am trying to add Account,Contact and Oppty records on runtime it's working fine.But how can I achieve it dynamically using sobjects type and describe methods i.e more dynamic without dependency.

public List<sObject> records;
records.add(new Account(Rating='Hot'));
records.add(new Contact(LastName='George'));
records.add(new Opportunity(Stage='Closed Won'));
insert records;
1

You can do that with help of describe call as below:

sObject sObj = Schema.getGlobalDescribe().get('<SobjectName>').newSObject();

Now you can put fields value dynamically:

sobj.put('Name', 'Test');

After that you can add to list and perform DML operation.

  • Thank you, so far I achieved this .I want to do it in a sobject list String sObjectName = 'Account'; Schema.SObjectType t = Schema.getGlobalDescribe().get(sObjectName); SObject s = t.newSObject(); s.put('Name','test'); insert s; – Salesforce Learner Jan 7 at 11:33
  • Your code is not readable....are you getting any issue ...? or you want to initialize in array? – Ayub Jan 7 at 11:41
  • String sObjectName = 'Account'; Schema.SObjectType t = Schema.getGlobalDescribe().get(sObjectName); SObject s = t.newSObject(); s.put('Name','test'); insert s; – Salesforce Learner Jan 7 at 12:01
  • Thanks for help.I want to set record based on external Id in the put method and use sObject list – Salesforce Learner Jan 7 at 12:02
  • do you want to perform upsert of list based on external id? – Ayub Jan 7 at 12:05
0

A related point is to take care how you order the types within the List<sObject> as otherwise, it is easy to run into this exception:

System.TypeException: Cannot have more than 10 chunks in a single operation.

Put all the SObjects of the same type adjacent to each other: if they are intermingled the type can change more than 10 times through the list.

This also means that no more than 10 types can be updated in a single DML call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.