You need to sign in to do that
Don't have an account?
How do I use Maps and Lists on a Trigger?
Hi,
I am receiving a error regarding too many SOQL queries when trying to upload several hundred contacts onto a campaign due to a trigger I have created.
From reading around the forum I believe that it is because my SOQL statement is inside a FOR loop which loops more times than the governor limits allow. I have read that I should perform the SOQL query outside of the FOR loop and use Lists and Maps to achieve what I require.
The trigger is pretty basic at the moment, however my coding skills are very limited and I'm not sure how to implement Lists or Maps.
I have posted my trigger below and if someone can instruct me on how to implement the Lists and Maps I would be very grateful.
trigger CampaignMemberUpdate on CampaignMember (after insert, after update) {
for (CampaignMember cm : trigger.new){
Contact contact = [SELECT Id from Contact where id = :cm.ContactId];
contact.Campaign_Member_Update_Date__c = cm.LastModifiedDate;
upsert contact;
}
}
Thanks,
Marco
Hi,
You have used queries in for loops. That is a basic error in salesforce.
Try this code.
If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.
Chamil's Blog
All Answers
Hi,
You have used queries in for loops. That is a basic error in salesforce.
Try this code.
If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.
Chamil's Blog
trigger CampaignMemberUpdate on CampaignMember (after insert, after update) {
list<contact> lstupdatecons = new list<contact>();
set<id> sIds = new set<id>();
for (CampaignMember cm : trigger.new){
sIds.add(cm.contactId);
}
list<contact> lstconts = [select id from contact where id in : sIds];
for(CampaignMember cm : trigger.new){
for(contact objcon : lstconts){
objcon.Campaign_Member_Update_Date__c = cm.LastModifiedDate;
lstupdatecons .add(objcon);
break;
}
}
if(lstupdatecons .size() > 0)
update lstupdatecons ;
}
try this
@chamil
using the upsert in a loop is also a flaw ...
@ Kiran
Thanks For showing the error. I forgot it. Now I corrected it.
Thanks again kiran
@Chamil @Kiran
Thanks for your combined input, I have used Chamil's updated code and it appears to work. Have marked the reply as a solution.
Regards,
Marco