+ Start a Discussion
sai tarunsai tarun 

Share Annual Revenue Amount to Child records(Contacts) Equally


Using Trigger
in an account ,assume you are having 5 contacts connected and you have Account Annual revenue assume10,000 rs amount.
Scenario is
distribute the annual revenue to child records equally(10,000/5),
when a child record is added then then, modify all child record amount (10000/6) who are conected with assosiated account 
when a child record is deleted then also chages will happed to contact fields(10000/4)....
please help me ..........
thanks in advance

thanks in advance.......
Best Answer chosen by sai tarun
Duke_SfdcDuke_Sfdc
Hi Sai,

Using for loop inside a for loop is not a good practice in Salesforce. please find the code to full fill your requirement.

trigger calculateAmount on Contact (after Insert,after delete) {
    
    list<contact> upcommingContacts=trigger.isInsert?trigger.new:trigger.old;
    
    list<contact> updatedContactList=new list<contact>();
    set<string> accountIdSet=new set<string>();
    for(contact c:upcommingContacts){
        if(c.accountid!=null){
            accountIdSet.add(c.accountId);
        }
    }
    
    map<string,integer> getAnnualRevenueMap=new map<string,integer>();
    map<string,integer> getNoOfContactPerAccount=new map<string,integer>();
    list<account> acclist=new list<account>([select id,AnnualRevenue,(select id,accountId,Amount__c from contacts) from account where id=:accountIdSet]);
    
    for(account a:acclist){
        if(a.AnnualRevenue!=null){
            getAnnualRevenueMap.put(string.valueOf(a.id),integer.valueOf(a.AnnualRevenue));
            getNoOfContactPerAccount.put(string.valueof(a.id),integer.valueOf(a.contacts.size()));
        }
    }
    
    for(contact con:[select id,Amount__c,accountid from contact where accountid in:accountIdSet]){
        if(con.accountId!=null){
            integer anRev=getAnnualRevenueMap.get(con.accountId);
            integer recordCount=getNoOfContactPerAccount.get(con.accountId);
            
            integer finalAnount=anRev/recordCount;
            con.Amount__c=finalAnount;
            updatedContactList.add(con);
        }
    }
    
    if(updatedContactList.size()>0){
        try{
            update updatedContactList;
        }
        catch(exception ex){
            system.debug(ex.getMessage());
        }
    }
}

If this answer will help you. Please mark your question as solved.

Thanks,
Duke_Sfdc

All Answers

RamakantRamakant
Hello,

Please try below code:
trigger DistributeRevenue on Contact (after insert, after delete) {
    Set<Id> accountIds = New Set<Id>();
	List<Contact> contactsToUpdate = New List<Contact>();
	for(Contact con:Trigger.New){
		accountIds.add(con.AccountId);
	}
	if(trigger.isDelete){
		for(Contact deleteContact:Trigger.Old){
			accountIds.add(deleteContact.AccountId);
		}
	}
	if(accountIds != null){
		List<Account> accountAndContactsToUpdate = [Select Id, AnnualRevenue__c, (Select id, Amount__c from Contacts) from Account Where ID IN :accountIds];
		for(Account acc: accountAndContactsToUpdate){
			for(Contact con : acc.Contacts){
				con.Amount__c = (acc.AnnualRevenue__c) / acc.Contacts.size();
				contactsToUpdate.add(con);
			}
		}
	}
}

Please mark as a best answer if helped. Do let me know in case of issues.

Regards,
Ramakant
sai tarunsai tarun
Thnx bro ,but o/p not showing as we exepected
i think you forgot to write -- update contactsToUpdate;
code is executed but amount__c field not updated............
RamakantRamakant
Try Below code:
trigger DistributeRevenue on Contact (after insert, after delete) {
    Set<Id> accountIds = New Set<Id>();
	List<Contact> contactsToUpdate = New List<Contact>();
	for(Contact con:Trigger.New){
		accountIds.add(con.AccountId);
	}
	if(trigger.isDelete){
		for(Contact deleteContact:Trigger.Old){
			accountIds.add(deleteContact.AccountId);
		}
	}
	if(accountIds != null){
		List<Account> accountAndContactsToUpdate = [Select Id, AnnualRevenue__c, (Select id, Amount__c from Contacts) from Account Where ID IN :accountIds];
		for(Account acc: accountAndContactsToUpdate){
			for(Contact con : acc.Contacts){
				con.Amount__c = (acc.AnnualRevenue__c) / acc.Contacts.size();
				contactsToUpdate.add(con);
			}
		}
	}
	update contactsToUpdate;
}

Hope this will work.
Mark best answer if worked.

Regards,
Ramakant​
Duke_SfdcDuke_Sfdc
Hi Sai,

Using for loop inside a for loop is not a good practice in Salesforce. please find the code to full fill your requirement.

trigger calculateAmount on Contact (after Insert,after delete) {
    
    list<contact> upcommingContacts=trigger.isInsert?trigger.new:trigger.old;
    
    list<contact> updatedContactList=new list<contact>();
    set<string> accountIdSet=new set<string>();
    for(contact c:upcommingContacts){
        if(c.accountid!=null){
            accountIdSet.add(c.accountId);
        }
    }
    
    map<string,integer> getAnnualRevenueMap=new map<string,integer>();
    map<string,integer> getNoOfContactPerAccount=new map<string,integer>();
    list<account> acclist=new list<account>([select id,AnnualRevenue,(select id,accountId,Amount__c from contacts) from account where id=:accountIdSet]);
    
    for(account a:acclist){
        if(a.AnnualRevenue!=null){
            getAnnualRevenueMap.put(string.valueOf(a.id),integer.valueOf(a.AnnualRevenue));
            getNoOfContactPerAccount.put(string.valueof(a.id),integer.valueOf(a.contacts.size()));
        }
    }
    
    for(contact con:[select id,Amount__c,accountid from contact where accountid in:accountIdSet]){
        if(con.accountId!=null){
            integer anRev=getAnnualRevenueMap.get(con.accountId);
            integer recordCount=getNoOfContactPerAccount.get(con.accountId);
            
            integer finalAnount=anRev/recordCount;
            con.Amount__c=finalAnount;
            updatedContactList.add(con);
        }
    }
    
    if(updatedContactList.size()>0){
        try{
            update updatedContactList;
        }
        catch(exception ex){
            system.debug(ex.getMessage());
        }
    }
}

If this answer will help you. Please mark your question as solved.

Thanks,
Duke_Sfdc
This was selected as the best answer
sai tarunsai tarun
HI,
Duke_sfdc
You followed beat practices bust ,
contact field not updated.......
please once check this in your system once,cause it looks like perfect but i didnt get exact output(amount__c field not updated)....
so please check it......if it is succeccuflly updated in your side,then fault will be in my side.........i want to know that.......
Duke_SfdcDuke_Sfdc
Hello sai tarun

Just wanted to know if you still encounter the same issue bcoz it's working properly on my system.

Please mark it as the best answer if your problem is solved.

Thanks,
Duke_SFDC