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
rishi jaykar 1rishi jaykar 1 

write A Trigger:

Scenario :

1) Make two number fields on contact object
Amount_X
Amount_Y

2) Make one picklist field "Type" , values ('Positive', 'Negative')

3) Make two number fields on account
Rollup_Amount_X
Rollup_Amount_Y
Rollup_Amount

4) Make one trigger on contact object, which will do following:
--> Sum all child of contact's field "Amount_X" and store in parent account's "Rollup_Amount_X" Where Type is "Positive"
--> Sum all child of contact's field "Amount_Y" and store in parent account's "Rollup_Amount_Y" Where Type is "Negative"
--> Sum all child of contact's field "Amount_X" + "Amount_Y" and store in parent account's "Rollup_Amount"
 
Suraj TripathiSuraj Tripathi
Hi Rishi,
Below is the trigger for the same. It is working fine in my Org.
 
Apex Trigger
trigger ContactTrigger on Contact (before insert , before update ,after insert ,after update) {
   if(Trigger.isafter && Trigger.isinsert){
        UpdateValue.test(Trigger.new);
    }
  else if(Trigger.isafter && Trigger.isupdate){
       UpdateValue.test(Trigger.new); 
     }
}

Apex Handler
public class UpdateValue {
    public static void test(List <Contact> cntlist){
        Decimal count = 0;
        set<Id> conId = new set<Id>();
        for(contact con :cntlist){
            conId.add(con.AccountId);
        }
        system.debug('conId>>>>>>>>>>>'+conId);
        Account AccList = [select id,Rollup_Amount_X__c from account where id in : conId Limit 1];
        system.debug('AccList>>>>>>>>>>>'+AccList);
        list <contact> ConList = [select id,Amount_X__c from Contact where AccountId =: AccList.id];
        system.debug('ConList>>>>>>>>>>>'+ConList);
        for(contact con :ConList){
            if(con.Amount_X__c!=Null)
            { 
                count=count+con.Amount_X__c;
            }
        }
        
        Account acc = new Account();
        acc.id=AccList.id;
        acc.Rollup_Amount_X__c=count;
        Update Acc;	
        system.debug('Acc>>>>>>>>>>>'+Acc);
    }
}



Hope it Helps you. Please mark this as solved so that it gets removed from the unanswered queue which results in helping others who are encountering a similar issue.

Regards ,
Suraj​