function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Suresh RaghuramSuresh Raghuram 

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.

Best Answer chosen by Admin (Salesforce Developers) 
vishal@forcevishal@force

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

vishal@forcevishal@force

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!

 

This was selected as the best answer
Suresh RaghuramSuresh Raghuram

Thank u vishal it helped