function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Chris Walters 9Chris Walters 9 

Chicken/Egg question - update objects of class Foo in before trigger

class LiveChatTranscript has fields AccountId and ContactId .
class Contact has field AccountId .
class Account has field Contact__c .  ( custom field - our business logic is such that a Contact will always relate to one and only one Account but an Account may not have a Contact )

class  LiveChatTranscriptHandler is where our trigger logic lives, including bulkBefore() and bulkAfter() .

an instance of LiveChatTranscript will always have AccountId set to an existing instance of Account. Account instance may or may not point to an existing Contact via Account.Contact__c .

Goal - for all new LiveChatTranscript instances find associated Accounts NOT pointing to an existing Contact, create Contacts with dummy-but-unique FirstName, LastName and Email fields , assign Contacts to Accounts and to LiveChatTranscript.

In a non-SF traditional language you'd do something like
for( LiveChatTranscript lct : List<LiveChatTranscript> {
    Account acc = getAccount( lct.AccountId);
    if( acc.Contact__c == null) {
        Contact con = new Contact();
        con.FirstName = magicUniqifier();
        con.LastName = magicUniqifier();
        con.Email = magicUniqifier();
        insert con;  
        // now con has an Id
        acc.Contact__c = con.Id;
        update acc;
        lct.ContactId = con.Id;
        update lct;
// now update Contacts based on some requirements baked into AdjustContact
for( LiveChatTranscript lct : List<LiveChatTranscript> {
    Contact con = getContact( lct.ContactId);
    AdjustContact( con);
    update con;

Turns out SF will let me write a bulkBefore that will create and insert Contacts but not =persist= them to the db. And moving that code to an bulkAfter will create, insert, and persist the Contacts but trying to  make the assignments to LiveChatTranscript.ContactId recursively triggers the handler again. 

Now there might be a sneaky way to achieve this because we're dealing with LiveChatTranscript , which I think only gets created at the completion of a LiveAgentSession - perhaps creating a LiveAgentSessionTrigger/LiveAgentSessionHandler and putting the Contact-creation logic there would do the trick. I might try that if all else fails. 

Ideas anyone?

Still-learning Chris