0

I have a controller with a constructor. Where i'm querying lead record with an id. When i'm trying to reference a field from this sObject I get "Variable does not exist: Email"

public Lead_Controller {
public sObject leadrecord {get;set;}
    public Lead_Controller(ApexPages.StandardController controller){
        string leadrecordId = controller.getRecord().id;
        leadrecord = [select id, name, Email from Lead where Id =:leadrecordId];
       if(leadrec.Email != null){
         //trying get the email here and got "Variable does not exist: Email"
       }
    }
}

any ideas? why would this happen?

2
  • Does the user running this code have access to the Email field? This smells like a permission issue. Commented Jun 12, 2018 at 17:36
  • @SebastianKessel yes, admin profile and it is a standard field on Lead, forgot to mention that. Commented Jun 12, 2018 at 17:38

2 Answers 2

4

That error often points to an unrelated syntax error in the code shortly before the field reference, which you should include in your question for more direct answers.

However, you have another issue here - you should change your leadrecord variable to be declared explicitly as a Lead. The type sObject has no property Email, so you'd have to do leadrecord.get('Email') to access it. It's better and easier to declare the correct type at compile time, which also will give you compiler checks and field dependencies tracked by the system.

4
  • Good catch there Commented Jun 12, 2018 at 17:39
  • ahh, I forgot to add the if condition which was causing the problem. But thanks for the solution and lesson. Commented Jun 12, 2018 at 17:55
  • @naruto-sfdc were you able to solve the underlying issue? If you want to edit your question to include the nearby lines of code, I'm sure one of us can spot it.
    – David Reed
    Commented Jun 12, 2018 at 18:00
  • @DavidReed by changing the leadrecord variable type from sObject to Lead did the trick. Commented Jun 12, 2018 at 18:05
0

Is it really necessary to make the additional query there ? ApexPages.StandardController addFields() method with the specified list of arguments already provides you with a record data. I suppose it will be enough in your case:

public Lead_Controller {

    public Lead leadrecord {get;set;}
    public Lead_Controller(ApexPages.StandardController controller){
        controller.addFields(new List<String>{'Email'});
        leadrecord = controller.getRecord();
        if(leadrec.Email != null){
           //record Email should be defined here
        }
    }
}
1
  • 1
    Thanks Alexander, i didnt know that approach. thanks for the tip. Commented Jun 12, 2018 at 20:07

You must log in to answer this question.

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