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
jcbuscheljcbuschel 

Rolling up data without a master-detail relationship

Sorry, I'm a bit of a newbie to SFDC development but was wondering if someone has a solution that I can use to roll-up data from a related list without a master-detail relationship between the two objects. I can't seem to find the answer on any existing discussion threads although there are a few people trying to similar things. 

 

The situation:

I have a related list of Contracts (standard object) on a custom object, Instruments. These Contracts have an End Date which I would like to roll-up to the associated Intrument record. Essenially I would like to show the MAX(Contract.End_Date) on the Instrument record for all Contracts assosciated with that Instrument. 

 

Obviously a Roll-up Summary Field won't work here because of the lack of a master-detail relationship, so I was thinking an APEX Trigger is the only option. Does any one have suggestions on how this can be accomplished? Do I need to go the APEX Trigger Route or is there an easier option? And if I have to use an APEX trigger, do you have any code examples I can reuse?


Thanks for your help!
Cam

CoryCowgillCoryCowgill

Apex Trigger is only way to accomplish summary this if you aren't using Master-Detail. It would be nice if formula fields would support this, but they dont. :(

 

1. Create a new field on the parent object called whatever (Children Count for example)

2. On your trigger for the child object, whenever you insert or delete children records update teh parent count - See below snippet.

 

Child_Object__c[] childs = trigger.new;
List<Id> accountIds = new List<Id>();
for(Child_Object__c child : childs)
{
 if(eng.AccountId != null)
 {
  accountIds.add(child.AccountId);
 }
}
List<Account> accts = [select Id, Name, Child_Count__c,(Select Id from Child_Object__r ) from Account where Id in :accountIds];
for(Account acct : accts)
{
  List<Child_Object__c> accountChildren = acct.Engagement__r;
  acct.Child_Count__c = accts.size();  
}
update accts;