The Scenario: I have a selectlist on my page (1 value) with a list of options. I want it to default with an option.
My page:
<apex:page controller="mycontroller"> <apex:selectlist value="{!SelectedItem}" size="1"> <apex:selectOptions value="{Items}" /> </apex:selectlist> </apex:page>
Now I know in the controller I could have a string variable and a setter and a getter method which will work like this:
public class MyController{ string S = 'Item1'; public string getSelectedItem(){ return s; } public void setSelectedItem(String s){ this.s = s; } public list<SelectOption> getItems (){ list<SelectOption> options = new list<SelectOption>(); options.add(new SelectOption('','Select one')); options.add(new SelectOption('Item1','Item1')); //repeat return options; } }
That will work it just seems… well like a lot of lines…
What I’m wonder is why doesn’t something like this work:
public class MyController{ public string SelectedItem {get;set;} public list<SelectOption> getItems (){ list<SelectOption> options = new list<SelectOption>(); options.add(new SelectOption('','Select one')); options.add(new SelectOption('Item1','Item1')); //repeat return options; } public MyController(){ SelectedItem = 'Item1'; }
I set the value of the string in the constructor instead of directly to the variable and collapsed the getter/setter… so why doesn’t this work the same? If I want ‘Item1’ to be the defaulted value what else could I do?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You’re example worked for me. You can chop down the lines a bit more if you want by initializing the variable in the same line (which is nice IMHO). Another thing you may want to note is you can disable a select option if you want to have a start “Select Stuff” text that isn’t itself selectable.
public class MyController{ private static final String OPT1 = 'Item1'; private static final String OPT2 = 'Item2'; private static final String START = 'Select One'; public String selectedItem { get; set; } { selectedItem = OPT1; } public List<SelectOption> options { get; private set; } { options = new List<SelectOption>(); options.add(new SelectOption(START, START, true)); // ==> option disabled options.add(new SelectOption(OPT1, OPT1)); options.add(new SelectOption(OPT2, OPT2)); } }
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0