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
Rocks_SFDCRocks_SFDC 

How to restrict the child records based on sum of field using Apex Trigger

Hi Developers,

I have product object and custom object(Designations__c). We have look up relationship between product and designation__c(Parent: Product, Child: Designation__c)
Fields:
On Product Object: Total Amount (Data Type:Currency)
On Designations Object: Amount(Data Type: Currency)

Now, The sum of amount of related designation records should not exceed 100 for an product record.

I want to applicable the functionality for Insert, Update and Delete operations.

Please help me out with the code.

Thanks,
Rocks
Best Answer chosen by Rocks_SFDC
sandeep sankhlasandeep sankhla
Hi Anil,

Please check and let me knwo if you afce any issue..also you can refer below code for example...
 
trigger ContactTrigger on Contact (before insert) {
	
	
	set<Id> AccountId = new set<Id>();
	map<Id, Decimal> mappAccToSum = new map<Id, Decimal>();
	
	for (Contact objC : trigger.new)
	{
			AccountId.add(objC.AccountId);
	}
	
	
	for(AggregateResult objAgg : [ select  AccountId, sum(Year__c) from Contact where AccountId IN:AccountId group by AccountId])
	{
		mappAccToSum.put((Id)objAgg.get('AccountId'), (Decimal)objAgg.get('expr0'));
		
	}
	
	for(Contact objC : trigger.new)
	{
			if(mappAccToSum.containskey(objC.AccountId))
			{
				
				if(mappAccToSum.get(objC.AccountId) > 100)
				{
					objC.addError('Parent Account Sum is greateer than 100');
				}
				
				
				
			}
	}
		
        
        
         
         
        
         
        
        
         
}

please check adn let me know if it helpos you..

Thanks,
Sandeep

All Answers

sandeep sankhlasandeep sankhla
Hi,

You can write a trigger on before insert, before update and before delete...

you can simplly rollup the sum adn chck if it crosses the 100 then using addError you can show the error to prevent the insertion and updation of child record.


Please implement and let me know if you face any issue in implementing the same.

Thanks,
Sandeep
Rocks_SFDCRocks_SFDC
Hi Sandeep,

Thank you for your reply !!!!

I unable to show an error message. I have displayed sum sucessfully on the Product.

Here is my code:

In code: I took "Opportunity" is the parent object and "Payments" is the child object

trigger OpportunityRollUpPayments on Payment__c (after delete, after insert, after update) {
 
  set<Id> OpportunityIds = new set<Id>();
 
  if(trigger.isInsert || trigger.isUpdate){
    for(Payment__c p : trigger.new){
      OpportunityIds.add(p.Opportunity__c);
    }
  }
 
  if(trigger.isDelete){
    for(Payment__c p : trigger.old){
      OpportunityIds.add(p.Opportunity__c);
    }
  }
 
  map<Id,Double> OpportunityMap = new map<Id,Double> ();
  for(AggregateResult q : [select Opportunity__c,sum(Amount__c)
    from Payment__c where Opportunity__c IN :OpportunityIds group by Opportunity__c]){
      OpportunityMap.put((Id)q.get('Opportunity__c'),(Double)q.get('expr0'));
  }
 
  List<Opportunity> OpportunitiesToUpdate = new List<Opportunity>();
  for(Opportunity o : [Select Id, Total_Payments__c from Opportunity where Id IN :OpportunityIds]){
    Double PaymentSum = OpportunityMap.get(o.Id);
    o.Total_Payments__c = PaymentSum;
    OpportunitiesToUpdate.add(o);
  }
 
  update OpportunitiesToUpdate;
}


Could you please check and help me out in displaying error message on "Payments" Object through the trigger itself.

Thanks,
Anil
sandeep sankhlasandeep sankhla
Hi,

You can make use of addError ..please check below link ho whe is throwing error for all records..

from your code you can come to know which childs should not proceed with insert and update so you can simply iterate them adn show the eror 

https://developer.salesforce.com/forums/?id=906F00000008zcBIAQ

Please check and let me know if you face any issue..

Thanks,
Sandeep
sandeep sankhlasandeep sankhla
Hi Anil,

Please check and let me knwo if you afce any issue..also you can refer below code for example...
 
trigger ContactTrigger on Contact (before insert) {
	
	
	set<Id> AccountId = new set<Id>();
	map<Id, Decimal> mappAccToSum = new map<Id, Decimal>();
	
	for (Contact objC : trigger.new)
	{
			AccountId.add(objC.AccountId);
	}
	
	
	for(AggregateResult objAgg : [ select  AccountId, sum(Year__c) from Contact where AccountId IN:AccountId group by AccountId])
	{
		mappAccToSum.put((Id)objAgg.get('AccountId'), (Decimal)objAgg.get('expr0'));
		
	}
	
	for(Contact objC : trigger.new)
	{
			if(mappAccToSum.containskey(objC.AccountId))
			{
				
				if(mappAccToSum.get(objC.AccountId) > 100)
				{
					objC.addError('Parent Account Sum is greateer than 100');
				}
				
				
				
			}
	}
		
        
        
         
         
        
         
        
        
         
}

please check adn let me know if it helpos you..

Thanks,
Sandeep
This was selected as the best answer
Rocks_SFDCRocks_SFDC
Thanks Sandeep.