I need to make a search input - which every character that printed on the keyboard will show the closest result.
for example :
If I printed "uni" all accounts that they names starting with "uni" will appear for selecting.
I wrote a javascript function that calls for a method in the controller for this task, but I don't sure that this is the best way to do it - since every letter I tap in my keyboard, is calling the controller and make a SOQL query.
Can anyone please help me to achieve a better way for this?
This is my code :
Page :
<apex:page controller="ExmpleController">
<script>
function search(){
doSearch();
}
</script>
<apex:form >
<apex:actionFunction name="doSearch" action="{!searchForAccounts}" reRender="accountTable"/>
<apex:pageBlock >
<apex:outputText >Account Name</apex:outputText>
<apex:inputText value="{!name}" onkeyup="search();"/>
<apex:pageBlockSection columns="3">
<apex:pageBlockTable id="accountTable" value="{!accounts}" var="acc">
<apex:column value="{!acc.Name}"/>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
And the Controller :
public class ExmpleController {
public list<Account> accounts { get; set; }
public String name { get; set; }
public ExmpleController(){
accounts = new list<Account>();
}
public pageReference searchAccounts(){
string query ='';
if(name !=''){
query = 'Select Name From Account Where Name like \''+name+'%\' LIMIT 5';
accounts = database.query(query);
}
else{
query = 'Select Name From Account LIMIT 5';
accounts = database.query(query);
}
return null;
}
}
Thanks!