Auto complete text box in Salesforce

Auto complete text box in Salesforce

Auto completion of text box is an important feature to be added in many projects.

Use the below codes in your project for auto completion of text box in Salesforce.
Apex Class:

Name: autoCompleteController

global class autoCompleteController 
{
    @RemoteAction
    global static SObject[] findSObjects(string obj, string qry, string addFields, string profilename) 
    {
        /* More than one field can be passed in the addFields parameter
           Split it into an array for later use */
        List<String> fieldList=new List<String>();
        if (addFields != ”)  
        fieldList = addFields.split(‘,’);
        
        /* Check whether the object passed is valid */
        Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
        Schema.SObjectType sot = gd.get(obj);
        if (sot == null) 
        {
            return null;
        }
        
        /* Creating the filter text */
        String filter = ‘ like ‘%’ + String.escapeSingleQuotes(qry) + ‘%”;
        
        /* Begin building the dynamic soql query */
        String soql = ‘SELECT Name’;
        
        /* If any additional field was passed, adding it to the soql */
        if (fieldList.size()>0) 
        {
            for (String s : fieldList) 
            {
                soql += ‘, ‘ + s;
            }
        }
        
        /* Adding the object and filter by name to the soql */
        soql += ‘ from ‘ + obj + ‘ where name’ + filter;
        
        if(profilename!=”)
        {
            //profile name and the System Administrator are allowed
            soql += ‘ and Profile.Name like ‘%’ + String.escapeSingleQuotes(profilename) + ‘%”;
            system.debug(‘Profile:’+profilename+’ and SOQL:’+soql);
        }
        
        /* Adding the filter for additional fields to the soql */
        if (fieldList != null) 
        {
            for (String s : fieldList) 
            {
                soql += ‘ or ‘ + s + filter;
            }
        }
        
        soql += ‘ order by Name limit 20’;
        
        system.debug(‘Qry: ‘+soql);
        
        List<sObject> L = new List<sObject>();
        try 
        {
            L = Database.query(soql);
        }
        catch (QueryException e) 
        {
            system.debug(‘Query Exception:’+e.getMessage());
            return null;
        }
        return L;
   }
}
Apex Component:

Name: autoComplete

<apex:component controller=”autoCompleteController”>

  <!– JQuery Files –>

  <apex:includeScript value=”{!URLFOR($Resource.jqueryui18, ‘js/jquery-1.7.1.min.js’)}” />

  <apex:includeScript value=”{!URLFOR($Resource.jqueryui18, ‘js/jquery-ui-1.8.18.custom.min.js’)}” />

  <apex:stylesheet value=”{!URLFOR($Resource.jqueryui18,’css/smoothness/jquery-ui-1.8.18.custom.css’)}”/>

  <!– Attributes Required For Component –>

  <apex:attribute name=”objectname” description=”The object name you want to look for.” type=”String” required=”true”/>

  <apex:attribute name=”additionalfield” description=”Any additional fields you’d like to search and include in the display.” type=”String” required=”false”/>

  <apex:attribute name=”profilename” description=”To filter on the basis of profile name and include in the display.” type=”String” required=”false”/>

  <apex:attribute name=”autocomplete_textbox” description=”The ID for the Autocomplete List Textbox.” type=”String” required=”true”/>

   <!– CSS Style –>

  <style>

    .ui-autocomplete-loading {background: white url({!$Resource.loadingIcon}) right center no-repeat;}

  </style>

  <!– Javascript –>

  <script type=”text/javascript”>

    var j$ = jQuery.noConflict();

    j$(document).ready(function()

    {

        var sObjects;

        var queryTerm;

        j$(esc(‘{!autocomplete_textbox}’)).autocomplete({

            minLength: 1,

            source: function(request, response) {

                        queryTerm = request.term;

                        autoCompleteController.findSObjects(“{!objectname}”, request.term, “{!additionalfield}”, “{!profilename}”, function(result, event){

                            if(event.type == ‘exception’)

                            {

                                  alert(event.message);

                            } else

                            {

                                 sObjects = result;

                                 response(sObjects);

                            }

                        });

                   },

            focus: function( event, ui ) {

                    j$(esc(‘{!autocomplete_textbox}’)).val( ui.item.Name );

                    return false;

                    },

            select: function( event, ui ) {

                        j$(esc(‘{!autocomplete_textbox}’)).val( ui.item.Name );

                        j$(esc(‘{!autocomplete_textbox}_lkid’)).val( ui.item.Id );

                        j$(esc(‘{!autocomplete_textbox}_lkold’)).val( ui.item.Name );

                        if (event.keyCode == 13) {

                            event.preventDefault();

                        }

                        return false;

                    },

         })

         .data( “autocomplete” )._renderItem = function( ul, item ) {

            var entry = item.Name;

            if(“{!additionalfield}” !=”)

            {

                j$.each(“{!additionalfield}”.split(“,”) , function(key, value) {

                    entry = entry + ” ” + item[value];

                });

            }

            //entry = entry + “</a>”;

            //entry = entry.replace(queryTerm, “<b>” + queryTerm + “</b>”);

            entry = entry.replace( new RegExp( “(” + queryTerm + “)” , “gi” ), “<strong>$1</strong>” );

            return j$( “<li></li>” )

                .data( “item.autocomplete”, item )

                .append( “<a>” + entry + “</a>”)

                .appendTo( ul );

        };

    });

    function esc(myid)

    {

           return ‘#’ + myid.replace(/(:|.)/g,’\\$1′);

    }

  </script>

</apex:component>


Static Resource:


Add a gif format loading image in Static resources with the name ‘loadingIcon’.





Download jqueryui18 file from the below link


http://www.4shared.com/file/9o5DuyQy/jqueryui18.html



which is to be added in Static Resources.



Visualforce Pages examples:


Example for <apex:inputText>:


<apex:inputText value=”{!memName}” id=”membNam” >
<c:autoComplete autocomplete_textbox=”{!$Component.membNam}” objectname=”Member__c” />
</apex:inputText> 


Example for <apex:inputfield>:



<apex:inputfield value=”{!Member__c.Name}” id=”memNam”>
        <c:autoComplete autocomplete_textbox=”{!$Component.memNam}” objectname=”Member__c” />
</apex:inputfield> 


Leave a Reply