function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Hazel LarotHazel Larot 

How do I write an apex code to display last 2 records using getRecords?

Hi,
I have very little experience in apex code/visualforce pages and need to update an existing code in our org. I need to change an apex code so that a drop down list will only display the last 2 records created for an object. The object is called ProgramCycles (which is created every year) and I need the last 2 ProgramCycles only to display in the list options. 
Current code looks like this:
public list<SelectOption> ProgramCycles = new list<SelectOption>();
public list<SelectOption> getProgramCycles()
    {
      if(ProgramCycles == null || ProgramCycles.size() <= 0)
        ProgramCycles = SelectOptions.GetProgramCycleListRecent();
        system.debug('xyzzy-in getProgramCycles')        ;
      return ProgramCycles;
    }

This code displays 11 list options, including 4 past records and 7 future records that have not been created yet. 
 
Best Answer chosen by Hazel Larot
Abdul KhatriAbdul Khatri
You VF page looks good, so you are saying the below code still don't give you results
 
public List<SelectOption> getProgramCycles() {
        if(ProgramCycles == null || ProgramCycles.size() <= 0) {
            for(Program_Cycle__c progCycle: [SELECT Id, Name FROM Program_Cycle__c 
                                             WHERE End_Date__c > today AND IsActive__c = true 
                                             ORDER BY Start_Date__c ASC LIMIT 2])
                ProgramCycles.add(new SelectOption(progCycle.Id, progCycle.Name));
        }
        
        system.debug(ProgramCycles);
        return ProgramCycles;
    }
You can put this declaration at the top of the class like I did above
List<SelectOption> ProgramCycles = new List<SelectOption>();

All Answers

Abdul KhatriAbdul Khatri
You haven't shared what is there in the GetProgramCycleListRecent to get the understanding of your thoughts?
Hazel LarotHazel Larot
Hi @Abdul,  the GetProgramCycleListRecent() displayed in drop down list (top to bottom) are: Summer2021, AS2021, Summer2020, AS1920, Summer2019, AS1819, AS1718, Summer2018, Summer2017, AS1617.  The only real records here are the last 4.  The change I need is for the last 2 actual records to be displayed in the list options: AS1718 & Summer2018.
Narender Singh(Nads)Narender Singh(Nads)

What you can do is manually filter the list if the options in that dropdown list are static by iterating through the list.
Your code should look something like this:
public list<SelectOption> ProgramCycles = new list<SelectOption>();

public list<SelectOption> getProgramCycles()
    {
      list<SelectOption> TempProgramCycles = new list<SelectOption>();
      if(ProgramCycles == null || ProgramCycles.size() <= 0){
          TempProgramCycles = SelectOptions.GetProgramCycleListRecent();
          system.debug('xyzzy-in getProgramCycles');
      }
      for( SelectOption obj: TempProgramCycles ){
         if(//Here put your condition to filter the list, for example: obj.name=='AS1718')
              ProgramCycles.add(obj);
      }
      return ProgramCycles;
    }

Let me know if it helps.
Thanks.
Abdul KhatriAbdul Khatri
OK If I understood correctly You dropdown List will be see like this. I am not sure if you mistype there. Here is your values

Summer2021
AS2021
Summer2020
AS1920
Summer2019
AS1819
AS1718
Summer2018,
Summer2017
AS1617

But I think you meant the below. Keeping the below undestanding I have following questions before providing you solution
  • You mentioned 11 list options but theser are 10.
  • You mentioned you wanted to see last 2 options which from this perspective should be Summer 2017 and AS2017, so I am not sure why you said you wanted to see  AS1718 & Summer2018 from the above list.
  • You mentioned 7 future but here are 8 future records
  • The GetProgramCycleListRecent funtion will always give me 10 records like Summer9999, AS9999
Summer2021
AS2021
Summer2020
AS2020
Summer2019
AS2019
Summer2018,
AS2018
Summer2017
AS2017

 
Hazel LarotHazel Larot
Thanks @Narender for the suggested solution, but the ideal options in the dropdown list are not static and filtering them manually would mean updating the code everytime a new ProgramCycle is created because the last 2 actual records should be in the dropdown list.
Hazel LarotHazel Larot
Hi @Abdul, sorry I made a mistake in saying 11 options, you are correct, it's actually 10 and they appear exactly as you listed them in the first group. To give you more context about the ProgramCycles object, we create a pair of records every fiscal year (July-June), one in the Summer and one in the Fall. The Summer ProgramCycle is named with the year (like Summer 2017) while the fall ProgramCycle is named similar to the school year, like SY 2017-2018 is named AS1718 in our org. Right now, we have Summer 2018 as our last created ProgramCycle. AS1819 will be created this coming fall. In the current drop down list, only the last 4 ProgramCycles are actual records:
AS1718
Summer2018
Summer2017
AS1617

The ideal dropdown list should only comprise of AS1718 and Summer2018, being the last 2 records created PrograCycles. I hope this gives it more clarity. Thanks!
 
Abdul KhatriAbdul Khatri
I created two method to get the possible Summer and fall values based on the part of the year you are accessing the dropdown.
I made following assumptions
  • The Summer starts from 22 June and Fall Starts from 20 Sept. 
  • Record created in the object ProgramCycles accordingly
In the method GetProgramCycleListRecent() you can make a lookup to the above values and only add those in the list option.

It may help you get going.

Here are the two Methods
 
public String getSummerFiscalYear() {

    Date summerBeginDate = Date.newInstance(Date.today().year(), 6, 22);
   
	return 'Summer' + ((Date.today() > summerBeginDate) ? String.valueOf(Date.today().year()) : String.valueOf(Date.today().year()-1));    
   
}

public String getFallSchoolYear(){

	Date fallBeginDate = Date.newInstance(Date.today().year(), 9, 20);    
    
    if(Date.today() > fallBeginDate) {
        return 'AS' + String.valueOf(Date.today().year()-1).right(2) + String.valueOf(Date.today().year()).right(2);
    }else{
        return 'AS' + String.valueOf(Date.today().year()-2).right(2) + String.valueOf(Date.today().year()-1).right(2);     
    }
}

Let me know. 
 
Hazel LarotHazel Larot
Hi @Abdul, this looks promising. Sorry I am total newbie on this, but how can I incorporate these methods to the existing code or bind the resulting list options to the ProgramCycles object?  There are other records down the line that are dependent on the selected option (example: selecting Summer2018 will result to a dropdown list of TrainingPrograms related to Summer2018).  
Abdul KhatriAbdul Khatri
If you share the code for me to look at and the impact part I will try to help you.
Narender Singh(Nads)Narender Singh(Nads)
Hi Hazel,
If I understood your requirement correctly and the way I see it, i can think of two solutions. I will share the simpler one and let's see if it helps you.
 
public list<SelectOption> ProgramCycles = new list<SelectOption>();

public list<SelectOption> getProgramCycles()
    {
      list<SelectOption> TempProgramCycles = new list<SelectOption>();
      if(ProgramCycles == null || ProgramCycles.size() <= 0){
          TempProgramCycles = SelectOptions.GetProgramCycleListRecent();
          system.debug('xyzzy-in getProgramCycles');
      }
     integer i=0;
      for(i=TempProgramCycles.size()-2; i<TempProgramCycles.size();i++ ){
        
              ProgramCycles.add(TempProgramCycles[i]);
      }
      return ProgramCycles;
    }


This code will you the last two records of the list returned by GetProgramCycleListRecent() Function.

Note: This code will only give the right results if and only if your function GetProgramCycleListRecent()  returns a list of records which are sorted by created date in ascending order. For descending order, the for loop statement will require few modifications.

Let me know if it helps.
Thanks.

Hazel LarotHazel Larot
Hi Nerender,
This code actually works to limit the results to 2 (although I will have to adjust that to -4 to list 4 options on the list since the ListRecent results listed them by alpha order instead of record creation date and I need Summer2018 and AS1718).  But when I tried to select an option, I got an error saying 
List index out of bounds: -2 
An unexpected error has occurred.

Also, the original code has defaulted the option to blank (this one had the first option pre selected, which I don't want).
If this error can be resolved, then this would really help me resolve this issue. THANKS!
Abdul KhatriAbdul Khatri
OK Here is what I can think you code should look like
 
public list<SelectOption> ProgramCycles = new list<SelectOption>();

public list<SelectOption> getProgramCycles()
{
    list<SelectOption> TempProgramCycles = new list<SelectOption>();
    
    if(ProgramCycles == null || ProgramCycles.size() <= 0){
        TempProgramCycles = SelectOptions.GetProgramCycleListRecent();
        system.debug('xyzzy-in getProgramCycles');
    }
    integer i=0;
    for(i = 0; i < TempProgramCycles.size() ; i++){

        if(TempProgramCycles[i] == getSummerFiscalYear() || TempProgramCycles[i] == getFallSchoolYear())        
            ProgramCycles.add(TempProgramCycles[i]);
    }
    return ProgramCycles;
}

public String getSummerFiscalYear() {

    Date summerBeginDate = Date.newInstance(Date.today().year(), 6, 22);
   
    return 'Summer' + ((Date.today() > summerBeginDate) ? String.valueOf(Date.today().year()) : String.valueOf(Date.today().year()-1));    
   
}

public String getFallSchoolYear(){

    Date fallBeginDate = Date.newInstance(Date.today().year(), 9, 20);    
    
    if(Date.today() > fallBeginDate) {
        return 'AS' + String.valueOf(Date.today().year()-1).right(2) + String.valueOf(Date.today().year()).right(2);
    }else{
        return 'AS' + String.valueOf(Date.today().year()-2).right(2) + String.valueOf(Date.today().year()-1).right(2);     
    }
}

Hazel LarotHazel Larot
Hi Abdul,
I copied this code and got a compile error: Comparison arguments must be compatible types: System.SelectOption, String at line 703 column 30 which started from this part:
integer i=0;
    for(i = 0; i < TempProgramCycles.size() ; i++){

        if(TempProgramCycles[i] == getSummerFiscalYear() || TempProgramCycles[i] == getFallSchoolYear())        
            ProgramCycles.add(TempProgramCycles[i]);
    }
    return ProgramCycles;
Abdul KhatriAbdul Khatri
Sorry my bad

Please note SelectOptions take signature as (value, lable). In the code below I am matching with the value (.getValue()). If somehow in your case if it is a lable then you can change that to lable like .getLabel()
 
public list<SelectOption> ProgramCycles = new list<SelectOption>();

public list<SelectOption> getProgramCycles()
{
    list<SelectOption> TempProgramCycles = new list<SelectOption>();
    
    if(ProgramCycles == null || ProgramCycles.size() <= 0){
        TempProgramCycles = SelectOptions.GetProgramCycleListRecent();
        system.debug('xyzzy-in getProgramCycles');
    }
    integer i=0;
    for(i = 0; i < TempProgramCycles.size() ; i++){

        if(TempProgramCycles[i].getValue() == getSummerFiscalYear() || TempProgramCycles[i].getValue() == getFallSchoolYear())        
            ProgramCycles.add(TempProgramCycles[i]);
    }
    return ProgramCycles;
}

public String getSummerFiscalYear() {

    Date summerBeginDate = Date.newInstance(Date.today().year(), 6, 22);
   
    return 'Summer' + ((Date.today() > summerBeginDate) ? String.valueOf(Date.today().year()) : String.valueOf(Date.today().year()-1));    
   
}

public String getFallSchoolYear(){

    Date fallBeginDate = Date.newInstance(Date.today().year(), 9, 20);    
    
    if(Date.today() > fallBeginDate) {
        return 'AS' + String.valueOf(Date.today().year()-1).right(2) + String.valueOf(Date.today().year()).right(2);
    }else{
        return 'AS' + String.valueOf(Date.today().year()-2).right(2) + String.valueOf(Date.today().year()-1).right(2);     
    }
}

 
Hazel LarotHazel Larot
Hi Abdul,
This compiled successfully, but the resulting list options are now empty like this:
User-added image
With Narender's code, it looked like below, but created an error on Index out of bounds:
User-added image
 
Abdul KhatriAbdul Khatri
The only reason is the values are not matching. Seems like you have different format for the values instead of

Summer2017  It is Summer 2017
AS1617 it is After School 1617

The only difference between Narender's Code and My code is his code is very index based, you may end up getting that kind of error until n unless you put more checks.

Mine is information oriented, it will only fail if the data is not available which should not happen and if this happen that mean somewhere the process is broken.

Please confirm the how the information in the value (share the debug log) is saved and make the change in the two method getSummer... and getFall.... in the return value.

Otherwise it is your choice which suite you the best.
Abdul KhatriAbdul Khatri
Just change the methods to these and let me know
 
public String getSummerFiscalYear() {

    Date summerBeginDate = Date.newInstance(Date.today().year(), 6, 22);
   
	return 'Summer ' + ((Date.today() > summerBeginDate) ? String.valueOf(Date.today().year()) : String.valueOf(Date.today().year()-1));    
   
}

public String getFallSchoolYear(){

	Date fallBeginDate = Date.newInstance(Date.today().year(), 9, 20);    
    
    if(Date.today() > fallBeginDate) {
        return 'After School ' + String.valueOf(Date.today().year()-1).right(2) + String.valueOf(Date.today().year()).right(2);
    }else{
        return 'After School ' + String.valueOf(Date.today().year()-2).right(2) + String.valueOf(Date.today().year()-1).right(2);     
    }
}

 
Hazel LarotHazel Larot
I actually did that when I copied/updated the code, changed the return names to 'Summer ' and 'After School ', but still same results. It could be the specific dates you added:
Date summerBeginDate = Date.newInstance(Date.today().year(), 6, 22) for Summer and
Date fallBeginDate = Date.newInstance(Date.today().year(), 9, 20); for After School.

I know you were using this as an assumption, but are these dates based on record creation? We usually create Summer records around Jan-March and After School around July -September.
Hazel LarotHazel Larot
By the way @Abdul, thanks so much for your help so far and for being so patient with me.
Abdul KhatriAbdul Khatri
So from that perspective your dropdown must look like 
Summer 2018
After School 1617


So don't have specific process of getting those records created, I mean any specific date or scenario when new Program Cycle gets created every year.  You can alter the methods based on that.
Abdul KhatriAbdul Khatri
Would you mind sharing the Program Cycle Object and it's fields and few records?
Abdul KhatriAbdul Khatri
Man I have another idea and that should always work if you provide me little info I asked before about the Object Details and Record.
Hazel LarotHazel Larot
Hi Abdul,
Here are details about the Program Cycles object and some records (I was wrong about the future records not yet created, they were created by another department in our org in advance to accept some related records, my bad):
Object details
User-added image
Sample records
User-added image

 
Abdul KhatriAbdul Khatri
Why are you expecting Summer 2018 and not Summer 2017?
Hazel LarotHazel Larot
Hi Abdul,
This might give you a better idea of the Program Cycle records as they are now. 

User-added image
Hazel LarotHazel Larot
The last 2 Program records (based on chronological order and use) are After School 1718 and Summer 2018.  Which are in essence the most active program cycles in use for this app's purpose, so I want those 2 cycles ony to appear in the list options.
Abdul KhatriAbdul Khatri
Now this got me the clear picture.

I am not sure what is in your following Method GetProgramCycleListRecent
SelectOptions.GetProgramCycleListRecent();
Whatever you have change it to this
    List<SelectOption> returnValue = new List<SelectOption>();
    for(ProgramCycles__c progCycle : [SELECT Id, Program_Cycle_Name FROM ProgramCycles__c 
                                      WHERE End_Date__c > today AND IsActive__c = true 
                                      ORDER BY Start_Date__c ASC LIMIT 2])
    {
        returnValue.add(new SelectOption(progCycle.Id, progCycle.Program_Cycle_Name));
                                          
    }
               
    return returnValue;
Rest should all remain the same
Hazel LarotHazel Larot
Hi Abdul,
This gave me a compile error: Invalid type: Schema.ProgramCycles__c

I need to keep the variable declaration (because it's referenced down the line) and I just want to insert your code in place of the ListRecent method:

public list<SelectOption> ProgramCycles = new list<SelectOption>();
public list<SelectOption> getProgramCycles()
    {
        if(ProgramCycles == null || ProgramCycles.size() <= 0)
   //your code//     
        List<SelectOption> returnValue = new List<SelectOption>(); 
              for(ProgramCycles__c progCycle : [SELECT Id, Program_Cycle_Name FROM ProgramCycles__c 
                   WHERE End_Date__c > today AND IsActive__c = true 
                  ORDER BY Start_Date__c ASC LIMIT 2])
    {
        returnValue.add(new SelectOption(progCycle.Id, progCycle.Program_Cycle_Name));                                       
    }       
    return returnValue;
    }

======Just for your reference=======

Next set of codes referencing ProgramCycles:

public static List<StateProgram__c> lstStatePrograms = new List<StateProgram__c>();
public list<SelectOption> StatePrograms = new list<SelectOption>();
public list<SelectOption> getStatePrograms()
    {
     lstStatePrograms = ProgramLists.GetStatePrograms(ProgramCycleID);      
         
      StatePrograms = new List<SelectOption>();
      StatePrograms.add(new SelectOption('', ''));
      if(lstStatePrograms != null && lstStatePrograms.size() > 0)
      {
        for(StateProgram__c cycle : lstStatePrograms)
        {
             if(cycle.Id != null && cycle.Name != null)
                StatePrograms.add(new SelectOption(cycle.Id, cycle.Name));
        }
      }                                    
      
        return StatePrograms;
    }


public static List<SiteProgram__c> lstSitePrograms = new List<SiteProgram__c>();
public static list<SelectOption> SitePrgs = new list<SelectOption>();

public list<SelectOption> GetSiteProgramsList() {

SitePrgs = GetSiteProgramsList(ProgramCycleID,StateProgram,'');
return SitePrgs;
}

public list<SelectOption> GetSiteProgramsList(String strProgramCycleId, String strStateId, String strDistrictId)
  {
    lstSitePrograms = ProgramLists.GetSitePrograms(strProgramCycleId, strStateId, strDistrictId);      
         
      SitePrgs = new List<SelectOption>();
      SitePrgs.add(new SelectOption('', ''));
      if(lstSitePrograms != null && lstSitePrograms.size() > 0)
      {
        for(SiteProgram__c cycle : lstSitePrograms)
        {
             if(cycle.Id != null && cycle.Name != null)
                SitePrgs.add(new SelectOption(cycle.Id, cycle.Name));
        }
      }                                    
      
        return SitePrgs;
  }
Narender Singh(Nads)Narender Singh(Nads)
Hi Hazel,
In the code snippet which abdul shared replace 'ProgramCycles__c' with the API name of your object, the API name seems to be incorrect.

Thanks.
Abdul KhatriAbdul Khatri
In the SOQL below, change the name of the object as per your schema. I am not sure what it is, it could be Program_Cycles__c  or whatever and it should not give you compile error.
 
for(Program_Cycles__c progCycle : [SELECT Id, Program_Cycle_Name FROM Program_Cycles__c 
                                      WHERE End_Date__c > today AND IsActive__c = true 
                                      ORDER BY Start_Date__c ASC LIMIT 2])
    {
        returnValue.add(new SelectOption(progCycle.Id, progCycle.Program_Cycle_Name));
                                          
    }

 
Hazel LarotHazel Larot
Hi Abdul,
The object API is Program_Cycle__c.  And should I replace returnValue with ProgramCycles since this is the current variable that holds that selected option and will be reference later down the line?

I changed my entire code to below and it keeps on erroring out on Program Cycle Name which is a standard field (tried different way of writing it, like Program_Cycle_Name or ProgramCycleName or the standard field name which is Name and its still giving an error as "variable does not exist".
======
public list<SelectOption> ProgramCycles = new list<SelectOption>();
public list<SelectOption> getProgramCycles()
    {
        if(ProgramCycles == null || ProgramCycles.size() <= 0) {
        List<SelectOption> ProgramCycles = new List<SelectOption>(); 
        for(Program_Cycle__c progCycle: [SELECT Id, Program_Cycle_Name FROM Program_Cycle__c 
                              WHERE End_Date__c > today AND IsActive__c = true 
                              ORDER BY Start_Date__c ASC LIMIT 2])
    
        ProgramCycles.add(new SelectOption(Program_Cycle_Name));
     }                                                        
    return ProgramCycles;
    }

User-added image
Hazel LarotHazel Larot
Hi Abdul,

I got the codes to compile successfully, but I am still getting the empty dropdown result:
===
public list<SelectOption> ProgramCycles = new list<SelectOption>();
public list<SelectOption> getProgramCycles()
    {
        if(ProgramCycles == null || ProgramCycles.size() <= 0) {
        List<SelectOption> ProgramCycles = new List<SelectOption>(); 
        for(Program_Cycle__c progCycle: [SELECT Id, Name FROM Program_Cycle__c 
                              WHERE End_Date__c > today AND IsActive__c = true 
                              ORDER BY Start_Date__c ASC LIMIT 2])
    
        ProgramCycles.add(new SelectOption(progCycle.Id, progCycle.Name));
     }                                                        
    return ProgramCycles;
    }
===
Result
User-added image
 
Abdul KhatriAbdul Khatri
Can you check if the you getting results in the ProgramCycles return variable or that is also coming out empty?
Hazel LarotHazel Larot
I was using the ProgramCycles return variable (instead of returnValue since that is the variable referenced in the visualforce page.
Narender Singh(Nads)Narender Singh(Nads)
Hi Hazel,
Try running your SOQL query in Query Editor and see if you get any results. It looks like your SOQL query is not returning any records.
Abdul KhatriAbdul Khatri
Can you check what you get when you run this SOQL in the Developer Console
 
SELECT Id, Name FROM Program_Cycle__c 
                              WHERE End_Date__c > today AND IsActive__c = true 
                              ORDER BY Start_Date__c ASC LIMIT 2

 
Hazel LarotHazel Larot
Hi Narander, Abdul,

I checked the query and it returned two program cycles and what I expected to appear:  After School 1718 and Summer 2018, which is very promising. So it must be the return variables?
Narender Singh(Nads)Narender Singh(Nads)

Hey Hazel,

This code should help you get your desired results.
 

public list<SelectOption> ProgramCycles{get;set;} //Write this line in the global scope of your class

//Initialize ProgramCycles in your constructor. Instead o It should look something like this:
public YourClassName(){
   ProgramCycles=new selectOption[]{};
   this.getProgramCycles();
}


public void getProgramCycles() {
        if(ProgramCycles == null || ProgramCycles.size() <= 0) {
         
            for(Program_Cycle__c progCycle: [SELECT Id, Name FROM Program_Cycle__c WHERE End_Date__c > today AND IsActive__c = true ORDER BY Start_Date__c ASC LIMIT 2]){
                 ProgramCycles.add(new SelectOption(progCycle.Id, progCycle.Name));
            }
        }                                                        
}

Thanks.
Hazel LarotHazel Larot
Hi Narender,
I am getting this error :  Compile Error: Void method must not return a value 
 
public list<SelectOption> ProgramCycles{get;set;}
public FastContactEntryPageController(){
     ProgramCycles=new selectOption[]{};
   this.getProgramCycles();
}

public void getProgramCycles() {
        if(ProgramCycles == null || ProgramCycles.size() <= 0) {
        for(Program_Cycle__c progCycle: [SELECT Id, Name FROM Program_Cycle__c 
                         WHERE End_Date__c > today AND IsActive__c = true 
                         ORDER BY Start_Date__c ASC LIMIT 2])
                ProgramCycles.add(new SelectOption(progCycle.Id, progCycle.Name));
            }
            return ProgramCycles;
        }



 
Narender Singh(Nads)Narender Singh(Nads)
Hi Hazel,
If you look at my code, there is no return statement because return type for my function is void. 
Remove the 'return ProgramCycles;' line from the code.
It should not give any errors then.
Hazel LarotHazel Larot
Hi Narender,
Sorry, I realized my mistake earlier and I did take out the return ProgramCycles line and tried again, but it created another error in the new instance created down the line called 
list<SelectOption> foo4 =  myPageCon.getProgramCycles();
I commented that out and I was able to compile successfully, but it's giving me empty results again.

This is my code now that still returned empty options:
public list<SelectOption> ProgramCycles{get;set;}
public FastContactEntryPageController(){
     ProgramCycles=new selectOption[]{};
   this.getProgramCycles();
}

public void getProgramCycles() {
        if(ProgramCycles == null || ProgramCycles.size() <= 0) {
        for(Program_Cycle__c progCycle: [SELECT Id, Name FROM Program_Cycle__c 
                         WHERE End_Date__c > today AND IsActive__c = true 
                         ORDER BY Start_Date__c ASC LIMIT 2])
                ProgramCycles.add(new SelectOption(progCycle.Id, progCycle.Name));
            }
           
        }

 
Narender Singh(Nads)Narender Singh(Nads)
Hi Hazel,
In the code you used above, add:
system.debug(progCycle.Id+'  '+progCycle.Name ); // Add just before line no. 12
system.debug(ProgramCycles); // Add after line no. 13

Run the VF page again and let me know what results are you getting in your debug logs.
Hazel LarotHazel Larot
Hi Narender,
Adding the first code is causing an error:
Variable does not exist: progCycle

Did I put them on the correct lines?
public list<SelectOption> ProgramCycles{get;set;}
public FastContactEntryPageController(){
     ProgramCycles=new selectOption[]{};
   this.getProgramCycles();
}

public void getProgramCycles() {
        if(ProgramCycles == null || ProgramCycles.size() <= 0) {
        for(Program_Cycle__c progCycle: [SELECT Id, Name FROM Program_Cycle__c 
                         WHERE End_Date__c > today AND IsActive__c = true 
                         ORDER BY Start_Date__c ASC LIMIT 2])
                         system.debug(progCycle.Id+'  '+progCycle.Name );
                ProgramCycles.add(new SelectOption(progCycle.Id, progCycle.Name));
           }
          system.debug(ProgramCycles);  
        }

 
Abdul KhatriAbdul Khatri
Hey Hazel,

Lack of concepts is causing all these communication happening.

I hope in the VF Page you are using the following html syntax
<apex:selectOptions value="{!ProgramCycles}" />

Then you no need to call anything in the constructor.

Mind it if you didn't understand the code properly. There are misguided people here who just jump on to the bang wagon without understanding the requiement and provide bad solution. They even violate the basic knowledge of apex which may cause you problem in future.

My perspective I don't see any reason the following code doesn't work
 
List<SelectOption> ProgramCycles = new List<SelectOption>();
    public List<SelectOption> getProgramCycles() {
        if(ProgramCycles == null || ProgramCycles.size() <= 0) {
            for(Program_Cycle__c progCycle: [SELECT Id, Name FROM Program_Cycle__c 
                                             WHERE End_Date__c > today AND IsActive__c = true 
                                             ORDER BY Start_Date__c ASC LIMIT 2])
                ProgramCycles.add(new SelectOption(progCycle.Id, progCycle.Name));
        }
        
        system.debug(ProgramCycles);
        return ProgramCycles;
    }

You can try using the following examples and compare it with your pages and controller. You can run the below in your org too.

Simple VF Page (Sample)
<apex:page controller="ProgramCycleController" >
    <apex:form id="form"> 
        <apex:selectList id="programcycle" label="progarmcycle" multiselect="false">
            <apex:selectOptions value="{!ProgramCycles}" />
        </apex:selectList>
    </apex:form>                   
</apex:page>

Here is the controller with the exact code, no constructor
 
public class ProgramCycleController {
    
    List<SelectOption> ProgramCycles = new List<SelectOption>();
    public List<SelectOption> getProgramCycles() {
        if(ProgramCycles == null || ProgramCycles.size() <= 0) {
            for(Program_Cycle__c progCycle: [SELECT Id, Name FROM Program_Cycle__c 
                                             WHERE End_Date__c > today AND IsActive__c = true 
                                             ORDER BY Start_Date__c ASC LIMIT 2])
                ProgramCycles.add(new SelectOption(progCycle.Id, progCycle.Name));
        }
        
        system.debug(ProgramCycles);
        return ProgramCycles;
    }
}
Narender Singh(Nads)Narender Singh(Nads)
Hi Hazel,

Include those lines within the scope of your for loop
Like this:
for(Program_Cycle__c progCycle: [SELECT Id, Name FROM Program_Cycle__c WHERE End_Date__c > today AND IsActive__c = true  ORDER BY Start_Date__c ASC LIMIT 2])
{
                 system.debug(progCycle.Id+'  '+progCycle.Name );
                ProgramCycles.add(new SelectOption(progCycle.Id, progCycle.Name));
}
Hazel LarotHazel Larot
This is the visualforce page code that displays and accepts input for the ProgramCycles list options:
 
<apex:pageBlockSectionItem >
            <apex:outputlabel value="Program Cycle:" for="cmbProgramCycle"/>
    <apex:outputPanel styleClass="requiredInput" layout="block">
    <apex:outputPanel styleClass="requiredBlock" layout="block"/>                   
            <apex:selectList id="cmbProgramCycle" value="{!ProgramCycleId}" size="1" >
            <apex:selectOptions value="{!ProgramCycles}"/>
            <apex:actionSupport event="onchange" rerender="InputSec,panelMsg" status="Processing"/>            
            </apex:selectList>
     </apex:outputPanel>
             </apex:pageBlockSectionItem>

 
Abdul KhatriAbdul Khatri
You VF page looks good, so you are saying the below code still don't give you results
 
public List<SelectOption> getProgramCycles() {
        if(ProgramCycles == null || ProgramCycles.size() <= 0) {
            for(Program_Cycle__c progCycle: [SELECT Id, Name FROM Program_Cycle__c 
                                             WHERE End_Date__c > today AND IsActive__c = true 
                                             ORDER BY Start_Date__c ASC LIMIT 2])
                ProgramCycles.add(new SelectOption(progCycle.Id, progCycle.Name));
        }
        
        system.debug(ProgramCycles);
        return ProgramCycles;
    }
You can put this declaration at the top of the class like I did above
List<SelectOption> ProgramCycles = new List<SelectOption>();
This was selected as the best answer
Narender Singh(Nads)Narender Singh(Nads)
I don't see any reason why she is not getting the right results. Code should be working.
Hazel LarotHazel Larot
YEAH! Thanks Abdul, it finally worked! 

My code is like this:
public list<SelectOption> ProgramCycles = new list<SelectOption>();
public List<SelectOption> getProgramCycles() {
        if(ProgramCycles == null || ProgramCycles.size() <= 0) {
            for(Program_Cycle__c progCycle: [SELECT Id, Name FROM Program_Cycle__c 
                                             WHERE End_Date__c > today AND IsActive__c = true 
                                             ORDER BY Start_Date__c ASC LIMIT 2])
                ProgramCycles.add(new SelectOption(progCycle.Id, progCycle.Name));
        }
        
        system.debug(ProgramCycles);
        return ProgramCycles;
    }

 
Hazel LarotHazel Larot
It finally worked Narender. Thanks to you as well for helping out with the system.debug code.
Narender Singh(Nads)Narender Singh(Nads)
Am glad. :)
Hazel LarotHazel Larot
This is a completely different issue, but do you guys know (or point me to a link)  to a thread here that shows how I can use apex:inputField in VF page to accept non SObject fields? I will be using this for phone fields, which I want to keep the styling [ (555) 555-555 ] from the Contact SObject. It seems it's not possible to bind non SObject field with inputField which I really want to use instead of using JQuery static sources as I have seen in my research as workarounds.
Narender Singh(Nads)Narender Singh(Nads)
Salesforce doesn't allow binding of non Sobject field to apex:inputfield. What about using apex:inputtext? Won't that be able to fulfill your requirement?
Abdul KhatriAbdul Khatri
You are correct unfortunaterly.
Hazel LarotHazel Larot
My VF page currently is using inputText but my users are asking that the phone numbers for contacts should be standard phone format when they appear in reports.
Abdul KhatriAbdul Khatri
If it's the matter of report than I would suggest store this inputText to the field with the datatype Phone. It will automatically do the formatting on it's own.