We can not use rollup in lookup relationship. If you need roll-up functionality in lookup.
Create a field to show the rollup field value.
Here is the sample code
Here I have created a field "Total_Contact__c" in the account, to show total num of related contacts.
trigger accountTrigger in Account(Before Update) {
set<Id> accountIds = new set<Id>();
Map<Id, Account> accountMap = new Map<Id, Account>();
for (Account acc : Trigger.New) {
accountIds.add(acc.Id);
accountMap.put(acc.Id, acc);
}
List<Contact> contacts = [SELECT Id, AccountId FROM Contact WHERE AccountId IN: accountIds];
List<Account> toupdate = new List<Account>();
for (Id ids : accountIds) {
for (Contact Con : contacts) {
integer count = 0;
if (Con.AccountId == ids) {
count++;
}
}
//Here you can put the field name on which you need to update total number of contacts
accountMap.get(ids).Total_Contact__c = count,
toupdate.add(accountMap.get(ids));
}
Update toupdate;
}
Please try it.
I hope it helps you.
Kindly let me know if it helps you and please mark as Best Answer.
Hi Subodh Kumar,
We can not use rollup in lookup relationship. If you need roll-up functionality in lookup.
Create a field to show the rollup field value.
Here is the sample code
Here I have created a field "Total_Contact__c" in the account, to show total num of related contacts.
Please try it.
I hope it helps you.
Kindly let me know if it helps you and please mark as Best Answer.
Thanks and Regards,
Biswojeet
https://medium.com/@palanic/roll-up-summary-from-child-account-to-patent-account-d0d97114e883
https://sfdcpanther.wordpress.com/2017/09/26/how-to-write-a-rollup-summary-trigger-for-a-lookup-relationship/
https://blog.jeffdouglas.com/2009/07/30/roll-up-summary-fields-with-lookup-relationships-part-1/
https://andyinthecloud.com/2013/07/07/new-tool-declarative-rollups-for-lookups/
https://github.com/abhinavguptas/Salesforce-Lookup-Rollup-Summaries
https://medium.com/@palanic/roll-up-summary-from-child-account-to-patent-account-d0d97114e883
https://blog.jeffdouglas.com/2011/08/23/salesforce-trigger-when-rollups-summaries-not-possible/
http://varasi.com/salesforce/implementing-roll-up-summary-when-you-are-dealt-with-a-lookup-relationship/