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

Create dynamic listbox and SOQL query with its item

Hello All,


 I need to fetch all fields of contact object and form a list box like as follows



  • First Name
  • Last Name
  • Email
  • Phone 
by choosing a item from listbox need to form SOQL query with choosen field name for e.g. If I choose 
Email field then my query will be 
data = [Select Phone,Name,email,Title from contact where  Email = NULL   ]  ;  
return data; 
I need to add "Email"  field as dynamic value. Here I am getting value of listbox item in controller method, but I am not able to concate string in SOQL. 
Can anyone help me? for following task
1. Create listbox with fetch fields from Contact object?
2. Create a dynamic field name value in SOQL?


Message Edited by Dowithforce on 03-17-2009 03:09 AM
Best Answer chosen by Admin (Salesforce Developers) 

Not sure why you do not have a response yet, it is straight forward.  Here is how we have addressed this:


First, dynamic SOQL is easy:


String query = 'select ' + fieldList + ' from pat_Patient__c where id = \'' + id + '\'';

returnVal = (pat_Patient__c)Database.query(query); 


(of course protect the string from sql injection)


Second, building the dynamic Dropdown list:


fieldList = new List<SelectOption>();
fieldList.add( new SelectOption( '', '--None--')) ; 
Map<String, Schema.SObjectField> fMap = Schema.SObjectType.Contact.fields.getMap();
List<Schema.SObjectField> fTokens = fMap.values() ;

for( Integer i = 0 ; i < fTokens.size() ; i++ )
     Schema.DescribeFieldResult f = fTokens.get(i).getDescribe();
         if( f.isAccessible())  fieldList.add( new SelectOption( f.getName(), f.getLabel()));  



I hope this helps you, or anyone else who is trying to do something similar.