1

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;
            }
        }
    }
}
4
  • 1
    you don't have a trigger.new list in an apex class.
    – highfive
    Commented Apr 29, 2014 at 5:02
  • 1
    All of the trigger variables are global and they are available in this way, exactly as written, without being passed as a parameter to the method as long as this code is called from a trigger.
    – Mark Pond
    Commented Apr 29, 2014 at 6:28
  • @Shalini, do you have an Apex class in your org which has the name Lead in addition to the standard Lead sObject?
    – Mark Pond
    Commented Apr 29, 2014 at 6:33
  • No Mark, no other Apex classes with the name Lead. It was happening cos I had Trigger.new in my Apex class, as pointed out by Baskaran S. I changed my code and its working fine now. Thanks !
    – Shalini
    Commented Apr 29, 2014 at 6:40

1 Answer 1

4

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);
            }
        }
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .