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

in apex trigger, limit 1 is not working
Note: I'm very much a beginner at this, so please bear with me!
I am working on an apex trigger to add new leads to the appriate campaign, based on two of the lead fields: Trip Name and Trip Date. The campaign would be named Trip Name Trip Date, with a space between the name and the date.
Here's the trigger:
USER_DEBUG|[16]|DEBUG|The following exception has occurred: List has more than 1 row for assignment to SObject
But shouldn't the "limit 1" in the query fix that?
Thanks for your help!
I am working on an apex trigger to add new leads to the appriate campaign, based on two of the lead fields: Trip Name and Trip Date. The campaign would be named Trip Name Trip Date, with a space between the name and the date.
Here's the trigger:
trigger AddWebLeadToTripCampaign on Lead (after insert) { CampaignMember[] cms = new CampaignMember[0]; for(Lead record:Trigger.new) try{ if(!String.isBlank(record.Trip_Name__c)) { String cname = record.Trip_Name__c+' '+record.Trip_Date__c; cname = cname.trim(); System.debug('the value of cname is >>>>> ' + cname); List <Campaign> CIDs = [select id, name from Campaign where name = :cname limit 1]; System.debug('the list of CIDs is >>>>> ' + CIDs); String CID = [SELECT ID FROM Campaign].ID; cms.add(new CampaignMember(LeadId=record.Id,CampaignId=CID)); } insert cms; }catch (Exception e){ system.debug('The following exception has occurred: ' + e.getMessage()); } }For some reason it doesn't seem to be working. In the debug log I get an error:
USER_DEBUG|[16]|DEBUG|The following exception has occurred: List has more than 1 row for assignment to SObject
But shouldn't the "limit 1" in the query fix that?
Thanks for your help!
All Answers
I believe you should select into a Object instead of list. Try this:
Campaign CIDs = [select id, name from Campaign where name = :cname limit 1];
Note: If there are no rows returned limit 1 will cause error.
Thanks,
Y.Srinivas
The following exception has occurred: List has more than 1 row for assignment to SObject
Any ideas?
Ok. I think you not actually even using CIDs in yur code. You should try something like this to iterate in loop.
Old: New:
Thanks,
Y.Srinivas
Here's the line it's referring to:
for(Campaign CID = [select id, name from Campaign where name = :cname]){
What now?