Sunday 24 January 2021

Smart Search(Auto Complete) in Visualforce using JavaScript Remoting

 Hi,

Here we are going to learn how to prepare values from JavaScript for SmartSearch.

Scenario:

Fill "list" attribute from JavaScript Remoting.

Solution:

When we add  "list" attribute it adds <dataList>  in HTML in background automatically as shown below.


Sample Controller with Remote Method:

public class SmartSearchController {   

    public String selectedName{get;set;}

    @RemoteAction

    public static List<String> getAccounts() {

       List<String> accountNameList = new List<String>();

       for(Account actObj:[select id,name from Account limit 20]){

            accountNameList.add(actObj.Name);

        }

       return accountNameList;

    }

}

Sample Visualforce Page:

<apex:page docType="html-5.0" id="pg" cache="false" sidebar="false" showheader="false" standardStylesheets="false" controller="SmartSearchController">

    <apex:form id="frm">

        <apex:pageBlock title="Smart Search" id="pb">

            <apex:inputText list="" value="{!selectedName}" id="nameList"/>        

        </apex:pageBlock>

    </apex:form>

    <script>

window.onload = function(){

            Visualforce.remoting.Manager.invokeAction(

                    '{!$RemoteAction.SmartSearchController.getAccounts}',                     

                    function(result, event){

                        var options='';

                        if (event.status) {

                                for (var i = 0; i < result.length; i++) {

                                    options += '<option value="' + result[i] + '" />';

                                }

                                document.getElementById('pg:frm:pb:nameList:datalist').innerHTML = options;                              

                        } 

                    }, 

                    {escape: true}

                );

        }

    </script>

</apex:page>

In the above snippet we are using "dataList" id for preparing list of items.

Output:



Reference:

https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_js_remoting_example.htm

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_autocomplete



No comments:

Post a Comment

How to include a screen flow in a Lightning Web Component

 Hi, Assume  you have a flow called "Quick Contact Creation" and API Name for the same is "Quick_Contact_Creation". To i...