0

I have created a Class which has a constructor with a List variable to fetch data, the reason I have placed this in the constructor is so I don't need to make multiple SOQL calls.

I have created the class below but I don't believe this works correctly as I get this error:

classes/Notification_Utils.cls: Variable does not exist: monitoredAccounts

Code:

public with sharing class Notification_Utils {
    public Notification_Utils() {
        List<Account> monitoredAccounts = [SELECT Id Account];

    }

    public boolean isMonitoredAccount(Id recId)
    {
        for(APIObjectTrackingFields__c accountRec : monitoredAccounts) {
            if(accountRec.Id == recId)
            {
                return true;
            }
        }
        return false;
    }
}

Can someone advise what I'm doing wrong here?

7

You'll want to read about variables, but basically you need to make sure that your variable is in the correct scope. Scope defines which pieces of code can access the variable. As the general rule, the variable's scope is defined by the { and } that immediately surrounds the variable.

In your code, the scope of monitoredAccounts is the function:

public Notification_Utils() { // Start function scope
    List<Account> monitoredAccounts = [SELECT Id FROM Account];

} // End function scope

You can fix this by moving the variable to the class scope:

public with sharing class Notification_Utils { // Start class scope
    List<Account> monitoredAccounts;

    public Notification_Utils() {
        monitoredAccounts = [SELECT Id FROM Account];

    }

    public boolean isMonitoredAccount(Id recId)
    {
        for(APIObjectTrackingFields__c accountRec : monitoredAccounts) {
            if(accountRec.Id == recId)
            {
                return true;
            }
        }
        return false;
    }
}
| improve this answer | |
3

Your variable scoped only to the method it is created in, in this case, your Notification_Utils constructor. By moving where you declare the variable, you can set the scope to the entire class, allowing other instance methods to use this variable.

public with sharing class Notification_Utils {

    public List<Account> monitoredAccounts { get; set; }

    public Notification_Utils() {
        monitoredAccounts = [SELECT Id FROM Account];
    }

    public boolean isMonitoredAccount(Id recId)
    {
        for(APIObjectTrackingFields__c accountRec : monitoredAccounts) {
            if(accountRec.Id == recId)
            {
                return true;
            }
        }
        return false;
    }
}

You can read more about how variables are scoped in the documentation.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.