i got error when i try to use list from another method.

The error message say : Variable does not exist: perCode.Id

Here is my code:

    public List<selectOption> getPeriod() {        
    List<selectOption> options = new List<selectOption>(); 
    options.add(new selectOption('', '- None -')); 
    for (PYSETPAYPERIOD__c perCode : [SELECT Id, Name, Process_Flag__c FROM PYSETPAYPERIOD__c WHERE Process_Flag__c < 4 OR Process_Flag__c = NULL ORDER BY Name]) {         
        options.add(new selectOption(perCode.id, perCode.Name));       
    return options;

 public void RunPreprocess(){
        if(selectedPeriod == perCode.Id){
         //some logic here

Can anyone help me solve this one?

Thanks in advance.

1 Answer 1


perCode is "local" to the loop inside getPeriod, so it's not visible outside of that loop. Most likely, you'll want to write RunPreprocess like this:

public void runPreprocess() {
    if(selectedPeriod != null) {
        PYSETPAYPERIOD__c perCode = 
           [SELECT Name, Process_Flag__c  
            WHERE Id = :selectedPeriod];
        // rest of logic here

You can read more about scope under the Variables topic in the Developer's Guide.

Variables can be defined at any point in a block, and take on scope from that point forward. Sub-blocks can’t redefine a variable name that has already been used in a parent block, but parallel blocks can reuse a variable name. For example:

Integer i;
   // Integer i;  This declaration is not allowed

for (Integer j = 0; j < 10; j++);
for (Integer j = 0; j < 10; j++);
  • thanks @sfdcfox , hmm, but it still not working, when i already select which period i choose in my vfpage, it doesn't create a new record based on my choosen period.
    – Vikolai
    Sep 26, 2016 at 3:39
  • @Vikolai There's something about your code that's wrong, apparently, but we have no idea what. I'd probably recommend opening up a question that shows your code, and describes where you're stuck.
    – sfdcfox
    Sep 26, 2016 at 3:43
  • oke so i must open a new question and share my vfpage and my controller? also what i want to achieve and the errror message? right? @sfdcfox
    – Vikolai
    Sep 26, 2016 at 3:45
  • @Vikolai Yes, that'd be most useful. You can feel free to minimize the code just to the relevant parts if you can, but it should still be understandable with the omissions.
    – sfdcfox
    Sep 26, 2016 at 3:46
  • hmm oke! i already asked a new question sir @sfdcfox
    – Vikolai
    Sep 26, 2016 at 3:54

You must log in to answer this question.

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