Activity Forums Salesforce® Discussions How to create a child record from parent when external id is updated on parent record in Salesforce?

  • Piyush

    Member
    November 22, 2019 at 5:10 am
  • Yogesh

    Member
    November 22, 2019 at 7:54 am

    Hello,

    try this code below , hope  it will help you :-

    public static void syncInsuranceBuyers( List<BuyerWrapper> lstBuyers ) {

    List<Account> lstBuyers = new List<Account>();
    List<Contact> lstMembers = new List<Contact>();

    // Iterate over all the buyers to create a list for upserting the records
    for( BuyerWrapper bw : lstBuyers ) {

    // Create a new instance of Account sObject and add it into the list
    lstBuyers.add(
    new Account(
    Name = bw.name,
    ERP_Id__c = bw.IdFromExternalSystem
    // You can add addional fields mapping here
    )
    );

    // Iterate over the related members
    for( MemberWrapper mw : bw.members ) {
    // Create a new instance of Contact sObject and add it into the list
    lstMembers.add(
    new Contact(
    FirstName = mw.firstName,
    LastName = mw.lastName,
    ERP_Id__c = mw.IdFromExternalSystem,
    Account = new Account( ERP_Id__c = bw.IdFromExternalSystem )
    // You can add addional fields mapping here
    )
    );
    }
    }

    // Will have to make 2 different DML calls as we need to specify the ExternID field
    // which will be used to identify the existing records and will update them

    Database.UpsertResult[] resultsAcc = Database.upsert( lstBuyers, Account.Fields.ERP_Id__c );
    Database.UpsertResult[] resultsCon = Database.upsert( lstMembers, Contact.Fields.ERP_Id__c );

    /****
    * If it was just an insert opertaion then it could be achieved in a single DML
    *
    List<sObject> lstAllRecords = new List<sObject>();
    lstAllRecords.addAll( lstBuyers );
    lstAllRecords.addAll( lstMembers );
    Database.SaveResult[] results = Database.insert( lstAllRecords );

    * Since, upsert DML operation requires an external ID field defination as an extra parameter and we have 2 different fields so above can't be
    * achieved in a single DML call.
    ***/
    }

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos