Showing posts with label Set. Show all posts
Showing posts with label Set. Show all posts

Tuesday, 10 January 2023

Salesforce Collections Best Practices

 1. How many number of items can be added into a Salesforce Collection (List/Set/Map)?

     No Limit, Earlier it was 1000 but later it's been removed but keep in mind if you add more number of items it will lead to the Heap Size Error, Means too much data is being stored in memory during processing,6MB for synchronous transactions and 12MB for asynchronous transactions.

Fix have the SOQL query with as many as filter conditions and have the low number on the limit of records to be returned, To add to the list & Have the declaration with in required scope only.

Monday, 29 July 2019

Aggregate Result

Use Case : Contract is having multiple documents attached to the related list 'Notes & Attachment',Get the latest attachment document id for each contract.


The Below Code contains:
1.Set Value Assignment 
2.Map Creation
3.SOQL Group By & Having Clause
4.Aggregate Query 
5.Verifying the size of Aggregate Result/Map/Set values
6.Read the Aggregate Result
7.Add values to the Map  from aggregate result
8.Type Casting Aggregate Result
9.Return Type - Map
10.Reading the Map Value
Note : Aliasing the  SOQL field possible only in Aggregate result
       
public static Map GetContractLatestAttachment(Set ContractIds) //Set Value Assignment
    {
        Map ContractAttachMap = new Map(); //Map Creation
        //Get the latest attachment record ID
        //Aggregate Query 
        //SOQL Group By & Having Clause
        AggregateResult[] contrAttAggResults = [SELECT Max(Id) Id,ParentId  FROM Attachment 
                                                Group By ParentId Having ParentId in:ContractIds];     
        //Verifying the size of AggregateResult values 
        if(contrAttAggResults.size()>0)
        {
            //Read the Aggregate Result
            for(AggregateResult aggResult : contrAttAggResults)
            {
            // Add values to the Map from Aggregate Result  
            // Type Casting Aggregate Result - Id as per map declaration
              ContractAttachMap.put((Id)aggResult.get('ParentId'), (Id)aggResult.get('Id')); 
            }        
        }
        return ContractAttachMap;//Return Type - Map
    }         

       
 
       
public void UpdateContractWithLatestAttachmentId()
{
 Map ContractAttachMap = GetContractLatestAttachment();
 //Reading the Map Value
 if(ContractAttachMap != null)
 attachId = ContractAttachMap.get(conRecord.Id);
}