Last active
October 18, 2022 11:27
-
-
Save mhamzas/cdd838a9dda2b131b719430596f69795 to your computer and use it in GitHub Desktop.
Dynamic Parent Child Insertion in single DML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Initiaing a new list to insert | |
List<sObject> insertList= new List<sObject>(); | |
//Account Object | |
sObject accObj = Schema.getGlobalDescribe().get('Account').newSObject(); | |
// Account Object Data mapping | |
accObj.put('Name','Test'); | |
accObj.put('ExtId__c','Test'); //External Id | |
// Adding the account to the list | |
insertList.add(accObj); | |
//Duplicate for Lookup | |
//To Prevent "MORE THAN 1 External Foriegn Key provided" error | |
sObject accObj_clone = Schema.getGlobalDescribe().get('Account).newSObject(); | |
accObj_clone.put('ExtId__c','Test'); | |
//Contact Object | |
sObject con = Schema.getGlobalDescribe().get('Contact).newSObject(); | |
con.put('LastName','Test Con'); | |
// Method to dynamically add parent-child lookup (having ExternalID) | |
// https://salesforce.stackexchange.com/questions/161801/add-dynamic-lookup-on-contact-to-sobject-with-external-id | |
SObjectField accLookup = Schema.getGlobalDescribe().get('Contact').getDescribe().fields.getMap().get('AccountId'); //Getting the relationshipName | |
con.putSObject(accLookup.getDescribe().getRelationshipName(),accObj_clone); //Adding a lookup Reference | |
insertList.add(con); | |
try{ | |
insert inserList; // DML | |
} catch(Exception e){ | |
System.debug(e); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment