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?
Attribution to: Salesforce Wizard
Possible Suggestion/Solution #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));
}
}
Attribution to: Ralph Callaway
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/4163