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
Rahul Luthra 1Rahul Luthra 1 

Flow to populate latest related record

Hello,  Kindly help me to understand how can we achieve the below scenario via flow?
I have a custom object DD which is currently associated with the account object using Master-Detail Relationship where we can have multiple DD's against each account.
Now, when a user creates a new opportunity and associates it to the account (using lookup), DD's data like date and status should be auto-populated on the opportunity custom fields from the latest DD's record created.
TIA
Eswar Venkat 2Eswar Venkat 2
trigger PopulateOpportunityFields on Opportunity (before insert, before update) {
    Map<Id, Account> accountMap = new Map<Id, Account>();
    
    for (Opportunity opp : Trigger.new) {
        if (opp.AccountId != null) {
            accountMap.put(opp.AccountId, null);
        }
    }
    
    if (accountMap.keySet().size() > 0) {
        accountMap.putAll([SELECT Id, (SELECT Id, Date__c, Status__c FROM DDs__r ORDER BY CreatedDate DESC LIMIT 1) FROM Account WHERE Id IN :accountMap.keySet()]);
    }
    
    for (Opportunity opp : Trigger.new) {
        if (opp.AccountId != null) {
            Account account = accountMap.get(opp.AccountId);
            if (account != null && account.DDs__r.size() > 0) {
                DD__c latestDD = account.DDs__r[0];
                opp.Date__c = latestDD.Date__c;
                opp.Status__c = latestDD.Status__c;
            }
        }
    }
}
 
Arun Kumar 1141Arun Kumar 1141
Hi Rahul,

You can follow the below steps to create Flow :
1. Start the flow when a new opportunity is created and associated with an account.
2. Use a 'Get Records' element to retrieve the related DD records for the associated account. In the element, set the following:
  • Object: DD
  • Criteria: Account ID is not equal to null
User-added image
3. Use a 'Get Records' element to retrieve the latest DD record from the previous step. In the element, set the following:
  • Object: DD
  • Criteria: Account__C equals the Account ID of the record from the previous step
User-added image
4. Use a 'Record Update' element to populate the custom fields on the opportunity record with the values from the latest DD record. In the element, set the following:
  • Object: Opportunity
  • Fields: DD Date and DD Status
User-added image
5. Save and activate the flow.
User-added image

Hope this will help.
Thanks!