What is your use case? Are you sure you need/want a trigger on the account object? It seems instead you would want a trigger on the contact objects firing - on insert where accountId is populated - on update where accountId is updated (firing two rollups if account id is changing from one value to another)
Yes, I want trigger on Account object. Using after update and after insert, i need to trigger to get number of contacts in count. That should be displayed in account.
trigger RollupSummarytrigger on Contact (after insert, after update, after delete) { Set<Id> accIds = new Set<Id>(); for (Contact c: trigger.new) { accIds.add(c.AccountId); } Map<id,Account> mapAcc = new Map<id,Account>([Select Name,NumberOfContacts__c,(Select Id from Contacts) from Account WHERE Id in: accIds ]); for (Account a: mapAcc.values()) { mapAcc.get(a.Id).NumberOfContacts__c =a.Contacts.size(); System.debug('Number of contacts:'+mapAcc.get(a.Id).NumberOfContacts__c); } update mapAcc.values(); }
Hi...., Thanks for sharing views, But i want trigger on account like (Trigger Trigger_Name On Account(After insert, After update) For count the contacts and display account object custom field...., Plz share ur views
trigger CountContacts on Account (before update)
{
CountContact.countCon(Trigger.new);
}
-----apex class
public class CountContact{
public static void countCon(List<Account> accList){
List<contact> con = [SELECT id,name,Accountid FROM Contact WHERE Accountid IN:accList];
for(Account acc:accList){
acc.NumberOfContact__c=con.size();
system.debug('no of Contacts--->'+acc.NumberOfContacts__c);
}
}
}
If you find your Solution then mark this as the best answer.
- on insert where accountId is populated
- on update where accountId is updated (firing two rollups if account id is changing from one value to another)
trigger RollupSummarytrigger on Contact (after insert, after update, after delete) {
Set<Id> accIds = new Set<Id>();
for (Contact c: trigger.new)
{
accIds.add(c.AccountId);
}
Map<id,Account> mapAcc = new Map<id,Account>([Select Name,NumberOfContacts__c,(Select Id from Contacts) from Account WHERE Id in: accIds ]);
for (Account a: mapAcc.values())
{
mapAcc.get(a.Id).NumberOfContacts__c =a.Contacts.size();
System.debug('Number of contacts:'+mapAcc.get(a.Id).NumberOfContacts__c);
}
update mapAcc.values();
}
//trigger on Account
trigger NumberContactsOnaccountUsingAccUpdtInsert on Account (before update)
{
Set<id> accIds = new Set<id>();
for(Account acc: trigger.new) {
accIds.add(acc.Id);
}
List<contact> lstCon = [SELECT id,name,Accountid FROM Contact WHERE Accountid IN:accIds];
for(Account a: trigger.new)
{
a.NumberOfContacts__c = lstCon.size();
system.debug('===no of Contacts====>'+a.NumberOfContacts__c);
}
}
Please Select mine is Best Answer If you Can fell.
"Try below Code."
Trigger
If you find your Solution then mark this as the best answer.
Thank you!
Regards,
Suraj Tripathi