This is a small programming challenge to demonstrate techniques/tools in Salesforce.
The only objects involved are standard Accounts and Contacts. Account has a new field on it, called Newest_Contact__c. This is a lookup field to Contact, and the challenge is to write code to automatically populate that field with the most recently added Contact on any particular Account. If there is more than one Contact inserted for the same Account in the same transaction, we don’t care which one becomes the Newest_Contact__c.
See Flow For Developers for details on the Flow and Apex solutions below.
Where code here is referencing items from the nebc namespace, that is using our open-source library Nebula Core. Most of the usage (e.g. the trigger framework) is quite light, so you can probably understand the code here without having to delve deep into the main library.
The LazyIterator implementation is a more complex concept from Nebula Core. For a (slighly out-dated) background on it, see Using Lazy Evaluation to Write Salesforce Apex Code Without For-Loops.
Each solution looks at the FirstName of the contact to determine whether it should handle that particular record. They expect "Apex", "Flow", or "Lazy" for the Apex, Flow, and LazyIterator implementations respectively.
The Apex solution is in a single class, ContactNewestContactApex. Tests are in ContactNewestContactApexTest
The Flow solution is in a number of Flows. Contact_Insert_Newest_Contact handles the insert scenario. Contact_Update_Newest_Contact handles update. Contact_Update_Newest_Contact_SObjectIndex is an improved version of the update-case, using an Apex Action to implement a Map.
There are Apex Actions in support of the Flows:
- FlowAssert and FlowAssertEquals call Apex asserts for writing tests in Flow
- FlowTestRecordSource, FlowGetTestRecord, and FlowGetTestRecords insert and return test data for Flows
- FlowOldRecords allows Flow access to the old records in an update
- FlowSObjectIndex, FlowSObjectIndexCreate, and FlowSObjectIndexGet allow the creation of an SObjectIndex and retrieval of records from it
Apex tests are in ContactNewestContactFlowTest
Flow tests are in Test_Contact_Newest_Contact_Single_Contact (run by TestContactNewestContactSingleContact) and Test_Contact_Newest_Contact_Two_Contacts (run by TestContactNewestContactTwoContacts).
The Apex LazyIterator solution is in a single class, ContactNewestContactLazy. Tests are in ContactNewestContactLazyTest
MIT, see LICENSE