You need to sign in to do that
Don't have an account?

Trigger on opportunity where contact related to account of comes in contact role
please help me to wriite a trigger on opportunity where Contact related to account of the opportunity comes in the contact role.
Hi
You can do that in this way,
trigger OppContact on Opportunity (after insert)
{
Opportunity op=trigger.new[0];
list<Contact> ct=[select id,accountid from contact where accountid=:op.accountid];
if(op.accountid!=null)
{
Opportunitycontactrole obj= new opportunitycontactrole();
obj.contactid=ct[0].id;
obj.Opportunityid=op.id;
insert obj;
}
}
Thanks
All Answers
Hi
You can do that in this way,
trigger OppContact on Opportunity (after insert)
{
Opportunity op=trigger.new[0];
list<Contact> ct=[select id,accountid from contact where accountid=:op.accountid];
if(op.accountid!=null)
{
Opportunitycontactrole obj= new opportunitycontactrole();
obj.contactid=ct[0].id;
obj.Opportunityid=op.id;
insert obj;
}
}
Thanks
That's hugely helpful. Is there a way to modify the trigger so that it pulls down all of the Contacts on the Account (perhaps returning a value for the number of contacts and then running a loop to add them)?
Hi
You can do that in this way
trigger OppContact on Opportunity (after insert)
{
Opportunity op=trigger.new[0];list<Contact> ct=[select id,accountid from contact where accountid=:op.accountid];
list<opportunityContactrole> lstcon = new list<OpportunityContactRole>();
Opportunitycontactrole obj;i
f(op.accountid!=null)
{
for(Contact objContact : ct)
{
obj= new opportunitycontactrole();
obj.contactid=objContact.id;
obj.Opportunityid=op.id;
lstcon.add(obj);
}
if(lstcon.size()>0){
insert lstcon;}}}
Thank you again for the help - it works as advertised. Ideally we would have this trigger run on the Opportunity each time it's modified - I replaced (after insert) witth (after update) which works, only a little too well - each time the record is saved, it bring in another listing for each of the contacts so they appear to have duplicate listings. I don't know if this effects reporting or anything else negatively, but it definitely does not look right. Is it possible for the trigger to check against the current contact roles OR set it to run (after update) but only at certain stages, to limit the amount of times the contacts are loaded?
Thank you for all of the assistance.