1

I have a rest class that creates Account records, related Contacts and a related Custom Object 'Customer__c'.

I am able to upsert Accounts based on an External Id. How can I upsert the Contact related list and Customer__c related list records based on External ids?

Here's the class:

@RestResource(urlMapping='/Order/*')
global with sharing class OrderWebServicesV2 {

private class OrderWrapper {
    Account account;
    list<ContactWrapper> contacts;
}

private class ContactWrapper {
    Contact contact;
    list<Customer__c> customers;
}

@HttpPost
global static String doPost() {

    OrderWrapper container = (OrderWrapper)System.JSON.deserialize(
        RestContext.request.requestBody.tostring(), 
        OrderWrapper.class);

    Account acc = container.account;
    upsert acc MyExternalId__c;

    list<Contact> contactsToInsert = new list <Contact>();
    for (ContactWrapper wcon :container.contacts) {
        wcon.contact.accountId = acc.id;
        contactsToInsert.add(wcon.contact);
    }
    upsert contactsToInsert;

    //now wrapper list contains contact ids
    list<Customer__c> customersToInsert = new list <Customer__c>();
    for (ContactWrapper wcon :container.contacts) {
        for (Customer__c customer :wcon.customers) {
            customer.Contact__c = wcon.contact.id;
            customersToInsert.add(customer);
        }
    }
    upsert customersToInsert;
    return acc.id;
}
  }

How can I upsert the related lists using the same External Id 'MyExternalId__c'?

I tried using Database.insert but have not been successful. Thanks!

1 Answer 1

1

Try something like :

//to link account to contact based on external id
wcon.contact.account = new Account(MyExternalId__c = acc.MyExternalId__c); 
...
upsert contactsToInsert MyContactExternalId__c;  //if you have external id in contact

You must log in to answer this question.

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