Friday, March 10, 2017

Implement Enter Key to Execute Method in salesforce for search

How to Call Apex method on click of Enter button.
Solution :-
We can use the "keyCode==13" with actionfuction to call the apex method on Enter Key event like below

Apex Class:
public with sharing class EnterSearchController {

    public string strKey {get;set;}
    public List<Account> lstAccount {get;set;}
    public EnterSearchController()
    {
        lstAccount = new List<Account>();
    }

    public pageReference cancel()
    {
        return new pageReference('/001/o');
    }
   
    public void search()
    {
        if( strKey != null && strKey !=''  )
        {
            String wildcard = '%'+strKey+'%';
            lstAccount = [select id,name from account where name like :wildcard  ] ;
        }
       
    }

}
Visualforce Page:

<apex:page controller="EnterSearchController" >
    <apex:form >
        <apex:pageBlock >
        <apex:actionFunction action="{!search}" name="actionFunction" />
       
            <apex:pageBlockSection >
                <apex:inputText value="{!strKey}" onkeydown="if(event.keyCode==13){this.blur();actionFunction();}" />
               
            </apex:pageBlockSection>
            <apex:pageBlockButtons >
                <apex:commandButton action="{!cancel}" value="cancel" />              
                <apex:commandButton action="{!search}" value="Search" />              
           
            </apex:pageBlockButtons>
           
            <apex:pageBlockSection columns="1" >
                <apex:pageBlockTable value="{!lstAccount }" var="acc">
                    <apex:column value="{!acc.name}"/>
                   
                </apex:pageBlockTable>
            </apex:pageBlockSection>
           
        </apex:pageBlock>
    </apex:form>
</apex:page>

No comments:

Post a Comment