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
Melissa HowardMelissa Howard 

Need Apex code the mimics roll up feature

Hi,

I have a custom object called A with a lookup relationship (not master/detail) with custom object b. I can't use a roll up but I need to count how many B records for each A record and then just set a field on A with that number. This should be simple to do but I am missing some steps. How to set this up (I need apex code so I have a starting point)?

TIA,
KaranrajKaranraj
Check this article for implementing rollup summary field for loopup relation https://developer.salesforce.com/page/Declarative_Rollup_Summary_Tool_for_Force.com_Lookup_Relationships
Vijay NagarathinamVijay Nagarathinam
Hi,

Try this code, it will count the child record counts.
 
trigger RollupSummaryOnWarehouse on LineItem__c (after insert , after update) 
{
set<id> lnset = new set<id>();
Id ss;

if(Trigger.isInsert)
{
for(LineItem__c ln : Trigger.new)
{
lnset.add(ln.ProductName__c);
}

map<id,Warehouse__c > lnMap = new map<id,Warehouse__c >([select id,name,Total_Stock__c,CountChild__c from Warehouse__c where id IN : lnset]);


for(AggregateResult ag : [select ProductName__c age,COUNT(Unit_Sold__c)totalSold FROM LineItem__c  where ProductName__c IN : lnset group by ProductName__c])
{
   ss = (Id)ag.get('age');
   lnmap.get(ss).CountChild__c  = Integer.valueOf(ag.get('totalSold'));
   
}

update lnmap.Values();
}



}
}