I have written a method which I will call in a Trigger.While trying to save this code as Apex class, I am getting the error " Error: Compile Error: Loop variable must be of type SObject at line 7 column 13"
My code goes as below ,appreciate any help, thanks
public class LeadBefore {
public static void UpdateChapterEmailAddress (){
set<Id> JDRFLocationId = new set<Id>();
List<Lead> vLstLead = new List<Lead>();
for(Lead vLead:trigger.new)
{
if(vLead.JDRF_Location__c != null)
{
JDRFLocationId.add(vLead.JDRF_Location__c);
vLstLead.add(vLead);
}
}
Map<Id, JDRF_Location__c> vMapIdJDRFLocat = new Map<Id, JDRF_Location__c>([Select Id, Name, General_Email_Address__c from JDRF_Location__c where Id In: JDRFLocationId]);
for(Lead vLead: vLstLead)
{
if(vMapIdJDRFLocat.containsKey(vLead.JDRF_Location__c))
{
vLead.Chapter_Email_Address__c = vMapIdJDRFLocat.get(vLead.JDRF_Location__c).General_Email_Address__c;
}
}
}
}
Attribution to: Shalini
Possible Suggestion/Solution #1
Its throwing this error because trigger.new is not available in your class Lead Before. trigger.new is only available in context of trigger. If you want to use it in LeadBefore->UpdateChapterEmailAddress() then you need to pass it as a parameter from your trigger.
Attribution to: AtulRajguru9
Possible Suggestion/Solution #2
since you took the logic out of trigger and used trigger.new in a class separately will not work. You need to pass the trigger.new as a parameter to the method inside of this class and assign to a list.
public static void UpdateChapterEmailAddress (List<Lead> l){
List<Lead> lstLead = l;
for(Lead vLead:lstLead)
{
if(vLead.JDRF_Location__c != null)
{
JDRFLocationId.add(vLead.JDRF_Location__c);
In your trigger,
LeadBefore .UpdateChapterEmailAddress(trigger.new);
Attribution to: Bforce
Possible Suggestion/Solution #3
The actual reason it failed compilation is because the compiler couldn't detect that it was iterating over a list of sObjects. The same code, with an explicit cast to the proper type, works fine.
That said, if the static method accepts a list or a map as a parameter it makes this code a bit easier to write unit tests against. Passing the trigger collections to the method is not a mandatory practice.
public class LeadBefore {
public static void UpdateChapterEmailAddress (){
set<Id> JDRFLocationId = new set<Id>();
List<Lead> vLstLead = new List<Lead>();
for(Lead vLead : (List<Lead>)trigger.new)
{
if(vLead.JDRF_Location__c != null)
{
JDRFLocationId.add(vLead.JDRF_Location__c);
vLstLead.add(vLead);
}
}
Attribution to: Mark Pond
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/33918