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

after Insert Trigger on same object
Hi Community,
I wrote a trigger on opportunity which will insert few fields on Opportunity it self grabbing the data from a contact object
Here my question is the following trigger is error free but looks to me not completly bulkified and not so efficient.
Can any body suggest the improvement and correct me if i am doing wrong.
Trigger optInsertContactData on Opportunity(after Insert){
set<Id> ids =new set<Id>();
for(opportunity op: Trigger.new){
ids.add(op.contactLookUpId);
}
List<opportunity> opList = new List<opportunity>();
List<Contact> cntList = new List<Contact>([Select x, y from Contact where Id IN: ids]);
opList[0].x = cntList[0].x;
opList[0].y = cntList[0].y;
Insert opList;
}
Thanks in advance for your precious time and suggestions.
Yes, this isn't bulkified. Simply because you have handled for a single record insertion. It won't work for multiple records because of this
opList[0].x = cntList[0].x;
opList[0].y = cntList[0].y;
Also, your trigger is on Opportunity and it is updating Opportunity itself. So it should be a before insert.
Trigger optInsertContactData on Opportunity(before Insert){
set<Id> ids =new set<Id>();
for(opportunity op: Trigger.new){
ids.add(op.contactLookUpId);
}
Map<Id, Contact> cntMap = new Map<Id, Contact>([Select x, y from Contact where Id IN: ids]);
for(Opportunity o : trigger.new)
{
o.x = cntMap.get(o.contactLookUpId).x;
o.y = cntMap.get(o.contactLookUpId).y;
}
}
Let me know if you have any questions!
All Answers
Yes, this isn't bulkified. Simply because you have handled for a single record insertion. It won't work for multiple records because of this
opList[0].x = cntList[0].x;
opList[0].y = cntList[0].y;
Also, your trigger is on Opportunity and it is updating Opportunity itself. So it should be a before insert.
Trigger optInsertContactData on Opportunity(before Insert){
set<Id> ids =new set<Id>();
for(opportunity op: Trigger.new){
ids.add(op.contactLookUpId);
}
Map<Id, Contact> cntMap = new Map<Id, Contact>([Select x, y from Contact where Id IN: ids]);
for(Opportunity o : trigger.new)
{
o.x = cntMap.get(o.contactLookUpId).x;
o.y = cntMap.get(o.contactLookUpId).y;
}
}
Let me know if you have any questions!
Thank u vishal it helped