You need to sign in to do that
Don't have an account?
agambeer singh
How to write trigger on Standard object opportunity to calculate number of opportunities connected to particular standard object contact ?
Whole Scenario is, i have to take one Custom field in standard object CONTACT named "NumberOfOpportunities". And need to display number of opportunities related to particular contact in this custom field.
{
Set <ID>conid = new Set <ID>();
if (trigger.isinsert)
{
for (Opportunity opp : trigger.new )
{
conid.add(opp.contactid);
}
}
if (trigger.isupdate)
{
for (Opportunity opp : trigger.old)
{
conid.add (opp.contactid);
}
}
if (trigger.isdelete)
{
for ( Opportunity opp : trigger.old )
{
conid.add (opp.contactid);
}
}
List <Contact> con = new List <Contact>([Select id, NumberofOpportunities__c, (Select id from Opportunities) from Contact Where ID IN : conid]);
for (Contact a : con)
{
a.NumberofOpportunities__c = a.Opportunities.size();
}
update con;
}
................................X................................................x............................................................X.......................................................................................
i have tried by writing above code and this is not working...........please help me.........................i am new to salesforce.
Prework: Make 'Count of Contacts' field with type as Number on Account Object.
trigger CountOfContactsRelatedToAccount on Contact (after insert, after delete, after Undelete) {
Set<Id> accId = new Set<Id>();
if(Trigger.isInsert || Trigger.isUndelete){
for(Contact con : Trigger.new){
accId.add(con.AccountId);
}
}
if(Trigger.isDelete){
for(Contact con : Trigger.old){
accId.add(con.AccountId);
}
}
List<Account> accList = [Select Id,Name,Count_of_Contacts__c,(Select id from contacts) from Account where Id IN : accId];
for(Account acc :accList){
acc.Count_of_Contacts__c = acc.contacts.size();
}
update accList;
}
Your Problem is similar like this.
If you found this helpful, Kindly mark it as best answer.
Thanks,
Tushar
Try below trigger Please Mark It As Best Answer If It Helps
Thank You!
I have done this code on account and contact before putting this question, it went well.
It is not working for contact and opportunity. If you see the code i provide is similar to one you providing.