+ Start a Discussion
Shephali SwarnkarShephali Swarnkar 

How to write find query...???

-----------------Controller----------------------
public class search_con 
{
 
  Public List<Contact> results{Get;set;}
  public String field_name{get;set {field_name=value;} }   
  public String keyword{get; set {keyword=value;}}
   
  public void search_now()
  {
     results=(List<Contact>)[FIND :keyword IN ALL FIELDS RETURNING CONTACT(NAME, ACCOUNT.NAME, Email, PHONE, FAX, Owner.Name, MobilePhone)][0];
     
  }
  
  public List<SelectOption> getItems() {
            List<SelectOption> options = new List<SelectOption>();
            options.add(new SelectOption('Name','Name'));
            options.add(new SelectOption('Email','Email'));
            options.add(new SelectOption('Phone','Phone'));            
            return options;
        } 
}

----------------------------VF------------------------------------
Input:<apex:inputText value="{!keyword}" />
  In:<apex:selectList multiselect="false" size="1" value="{!field_name}">                                                 
                      <apex:selectOptions value="{!items}"/>
                   </apex:selectList>
                   
  <apex:commandButton value="search" action="{!search_now}"/>
In above code I am able to do the search using input 'keyword' but how to use 'field_name' string so that i can find the input keyword in selected field only.i tried this
 
results=(List<Contact>)[FIND :keyword IN field_name FIELDS RETURNING CONTACT(NAME, ACCOUNT.NAME, Email, PHONE, FAX, Owner.Name, MobilePhone)][0];

but it is throwing error.

Thanks
 
daniel_hdaniel_h
You can't use SOSL to search specific fields. If that is your requirement, you should switch to SOQL.
Shephali SwarnkarShephali Swarnkar
Hi Daniel_h,
      In that case how i can write the query.(Please correct it because i m getting the proper syntax)
results=  [ Select NAME, ACCOUNT.NAME, Email, PHONE, FAX, Owner.Name, MobilePhone from Contact where field_name =: keyword];

Thanks
daniel_hdaniel_h
You can't dynamically include a field using a variable with this syntax. If you want to build your SOQL in the code, build out a string and then use Database.query. See https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic_soql.htm