Tuesday, December 6, 2016

Visualforce page to search for an Accounts by entering Account Name and Press Enter Key.


We can use the "keyCode==13" with actionfuction to call the apex method on Enter Key event.



Page:



<apex:page controller="SearchByPressingEnterKeyDemoController" >
    <apex:form >
        <apex:pageBlock >
        <apex:actionFunction action="{!search}" name="actionFunction" /> 
        
            <apex:pageBlockSection >
            <apex:panelGrid columns="2"> 
            <apex:outputText value="Enter Account Name:" />
                <apex:inputText value="{!strKey}" onkeydown="if(event.keyCode==13){this.blur();actionFunction();}" />
             </apex:panelGrid>   
            </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>

Controller:



public class SearchByPressingEnterKeyDemoController {
    public string strKey {get;set;}
    public List<Account> lstAccount {get;set;}
    
    public SearchByPressingEnterKeyDemoController(){
        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  ] ;
        }
    }
}


No comments:

Post a Comment