Monday, 22 August 2016

Enter Search | Enter Key to Execute Method in salesforce


Problem :-
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  ] ;
        }
        
    }

}

VF 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>



Other Related Link
1) http://developer.force.com/cookbook/recipe/submit-a-form-with-the-enter-key

No comments:

Post a Comment