You need to sign in to do that
Don't have an account?
Hazel 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.
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.
You can put this declaration at the top of the class like I did above
All Answers
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:
Let me know if it helps.
Thanks.
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
Summer2021AS2021
Summer2020
AS2020
Summer2019
AS2019
Summer2018,
AS2018
Summer2017
AS2017
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!
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
Let me know.
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.
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.
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!
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;
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()
This compiled successfully, but the resulting list options are now empty like this:
With Narender's code, it looked like below, but created an error on Index out of bounds:
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.
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.
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.
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
Sample records
This might give you a better idea of the Program Cycle records as they are now.
I am not sure what is in your following Method GetProgramCycleListRecent Whatever you have change it to this Rest should all remain the same
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;
}
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.
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;
}
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
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.
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?
Hey Hazel,
This code should help you get your desired results.
Thanks.
I am getting this error : Compile Error: Void method must not return a value
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.
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 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:
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.
Adding the first code is causing an error:
Variable does not exist: progCycle
Did I put them on the correct lines?
Lack of concepts is causing all these communication happening.
I hope in the VF Page you are using the following html syntax
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
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)
Here is the controller with the exact code, no constructor
Include those lines within the scope of your for loop
Like this:
You can put this declaration at the top of the class like I did above
My code is like this: