Skip to main content

Posts

Showing posts from September, 2024

How to define generic null check of fields ?

  Use Case : Lets say you have a requirement to copy modified field values from latest opportunity to Account , then how can you do field mapping effectively ?  Assumptions: We are not using any flows here.  Step - 1 Get all Account Ids from Opportunity Trigger/trigger helper Step -2 Query Account and Its related opportunity records, assume you want to define latest opportunity by LastStageChangeDate, you can use createdDate too. This will give account details and latest opportunity without the new values that has been modified. so this is basically old opportunity.  private static List < Account > getAccounts ( set < id > accountIdset ){     return [ SELECT id , Field_1__c , Field_2__c , Field_3__c , Field_4__c , PersonEmail , Phone ,                                             ( SELECT id , Field_1__c , Field_2__c , Field_3__c , ...

How to update only one latest child record's from list of Parent records ?

 This post is all about how to use aggregate query effectively or write less complex apex code. Use Case: Lets say you need to update latest case record of each opportunity and  you have been given list of opportunity Ids. One opportunity can have multiple cases. How can you do it? Approach - 1 If you are strong in SQL, you might be linking to use Group By Opportunity__c Order By CreatedDate Desc and Limit 1. SOQL does not support Order By limit along with Group By. Approach - 2 Using Map to hold Opportunity Id with latest Case Here is sample code  // List of Opportunity IDs List < Id > opportunityIds = new List < Id >{ 'oppId1' , 'oppId2' , 'oppId3' }; // Map to hold the latest Case for each Opportunity Map < Id , Case > latestCaseMap = new Map < Id , Case >(); // Query all cases related to the Opportunity IDs, sorted by CreatedDate descending to get the latest case first List < Case > cases = [     SELECT Id , Opport...