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
VNVN 

Problem with SelectOption

Hi,
 
We have a requirement where i need to display a drop down menu in a visualforce page. The drop down field should display values which is exact replica of values for the field Marketing Domain in the Accounts object. Iam trying to achieve this using selectList and selectOption tags and this is the piece of code that iam using in my controller class.
 
public List<SelectOption> getItems() {
                List<SelectOption> options = new List<SelectOption>();
                domain = [Select Marketing_Domain__c from Account];
                for(Account a:domain)
                 {
                 String b=a.Marketing_Domain__c;
                options.add(new SelectOption(b,b));
                }
                return options;
The variable items is fetched in page editor as shown below
 
<apex:selectList id="domain" size="1" >
<apex:selectOptions value="{!items}"/>
 </apex:selectList>
 
Iam getting exception here(Null Pointer). The selectOption is not taking anything other than string values. Is there any way that i can fetch and display the values stored in the variable 'domain'?
 
Please help its urgent.
 
Thanks in advance
Priya Nair
Best Answer chosen by Admin (Salesforce Developers) 
VNVN
Found the error now...it was a mistake in the syntax....Thanks a lot for your help Sham.
 
Regards
Priya Nair

All Answers

ShamSham
Probably the query is returning some null records
Try modifying the query as [Select Marketing_Domain__c from Account where Marketing_Domain__c != null]
VNVN

Thanks a lot Sham....it worked....Now the problem iam facing is that iam getting duplicate values....since in the for loop i have mentioned

for(Account a:domain)

options.add(...)

do you know how to restrict the loop to the correct number of variables fetched from the select statement.

Thanks again

Priya Nair

 

ShamSham
Probably you should use "Set"

Set<string> setOptions = new Set<string>();

for(Account a: [Select Query]) {
   setOptions.add(a.Domain);
}

for(string key : setOptions) {
  //add to Select
}
VNVN

Thanks Sham,

Iam getting this error now...

Compile Error: Incompatible element type String for collection of System.SelectOption at line 20 column 3

The code i wrote was...
 
public List<SelectOption> getItems() {
Set<string> setOptions = new Set<string>();
List<SelectOption> options = new List<SelectOption>();
for(Account a: [Select Marketing_Domain__c from Account where Marketing_Domain__c != null]) {
   setOptions.add(a.Marketing_Domain__c);
}
for(String key : setOptions) {
  options.add(key);
}
return options;
}
Is it correct?
 
Thanks
Priya Nair
VNVN
Found the error now...it was a mistake in the syntax....Thanks a lot for your help Sham.
 
Regards
Priya Nair
This was selected as the best answer