8

Trying to insert a new Account and it's Contact (maybe multiple Contacts?) at the same time.

While researching this, I've come across various posts that are close to the solution, such as:

Simultaneous Parent/Child Insert

One DML Operation

My own idea would be (only good for a SINGLE contact unless I create multiple sets of these fields):

  • Have equivelent fields for the needed-Contact on the Account (hidden) and then have Apex (or possibly Process Builder?) create the Account using those fields after the Account appears.

It may not even work for what I need (the Rootstock MRP plugin we're using is going to immediately sync the Account to Customer, and it may not see the Contact "in time"). It's still two operations. But it's the closest I have come up with.

Any idea?

2
  • Just add an External Id field on Account that you can specify.
    – Adrian Larson
    Nov 16, 2016 at 15:58
  • You're implying that if I use an ExternalID field on Account, and put the same on the Contact record, I can use that to relate the two, without having to query for the Account ID? That's still technically two inserts unless there is another part to this I'm unclear on. :-/
    – AMM
    Nov 16, 2016 at 16:00

1 Answer 1

9

If you have an External Id field on Account that you can specify, you can set the relationship via the Name Pointing Field (Account).

String externalId = '<some_value>';
Account namePointingReference = new Account(ExternalId__c=externalId);
Account parent = new Account(ExternalId__c=externalId, /*other fields*/);
Contact child1 = new Contact(Account=namePointingReference, /*other fields*/);
Contact child2 = new Contact(Account=namePointingReference, /*other fields*/);
insert new List<SObject> { parent, child1, child2 };

Note that you need to use a separate Account instance for the name pointing reference, because you can only specify the External Id field for the SObject you use in this way. This approach will only consume one DML Statement from your governor limits.

4
  • 1
    This answer got me thinking: Any idea how the triggers behave on this insert? Wich runs first? The account or the contacts? Are the contacts ids available on the account after trigger? Nov 16, 2016 at 16:20
  • 1
    @FernandoGavinho Those would be very good questions to post separately. It does seem obvious the Account triggers run first, but I'm not sure about the latter question.
    – Adrian Larson
    Nov 16, 2016 at 16:43
  • 1
    Done =D Nov 16, 2016 at 17:29
  • 1
    Fascinating. Thanks so much. The referenced post (Name Pointing Field) was pretty fascinating.
    – AMM
    Nov 16, 2016 at 20:09

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.