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
Darryl SinghDarryl Singh 

How does one set a SelectOption to "selected" in APEX?

Hi Everyone!
While building a list of SelectOptions of Users, all options default to unselected.  However, when the User matches the logged-on user, we need to set the SelectOption to selected.  How can this be done in the following code?


public List<SelectOption> getFSEOptions() {

  List<SelectOption> FSEoptions = new List<SelectOption>();

  for (Field_Service_Engineer__c f : [select id, user__r.name from Field_Service_Engineer__c

                                                             order by user__r.name]) {

    FSEoptions.add(new SelectOption(f.id,f.user__r.name));

  }
  return FSEoptions;

}

Best Answer chosen by Admin (Salesforce Developers) 
sornasorna

In the VF page, your code will look like this:

<apex:selectList value="{!selectedValue}" size="1">

<apex:selectOptions value="{!FSEOptions}"/>

</apex:selectList>

 

The value attribute on selectlist tag is used to capture as well as to set the selected value. So, from your controller assign the loggedin user's value to the "selectedValue" variable. 

All Answers

sornasorna

In the VF page, your code will look like this:

<apex:selectList value="{!selectedValue}" size="1">

<apex:selectOptions value="{!FSEOptions}"/>

</apex:selectList>

 

The value attribute on selectlist tag is used to capture as well as to set the selected value. So, from your controller assign the loggedin user's value to the "selectedValue" variable. 

This was selected as the best answer
Darryl SinghDarryl Singh

Hi Sorna,

 

I'm brand new to VF/APEX, so your answer clears up a lot of conceptual issues for me, too.  A million thanks - you rock!