+ Start a Discussion
Ashish Kumar YadavAshish Kumar Yadav 

Autocomplete I want to display Account name with sap customer code in vf page lookup


Hi Team,

My requirement is I want to display in account lookup account name with sap customer code but i am facing issue to display sap customer code .can anyone please help me regarding this.

Vf Page
=========

<apex:page controller="OrderAccountLookup" tabStyle="OrderAccountLookup__tab">
    <apex:includeScript value="{!$Resource.Jquery_06_09_17}"/>
    <style>
        .txtfield{width:65px; margin-bottom:5px;}
        
        table.bgmpop{
        border-collapse:collapse;
        border:1px solid #333;
        font-family:calibri; font-size:12px;
        }
        table.bgmpop th {
        border-collapse:collapse;
        background:#6B95A0; color:#fff;
        border-right:1px solid #fff; text-align:center;
        font-family:calibri; font-size:14px;
        padding:3px; border:1px solid #fff;
        }
        table.bgmpop td {
        color:#333; border:1px solid #ccc;
        font-family:calibri; font-size:12px;
        padding:3px; text-align:center;
        }
    </style> 
    
    <script>
  function confirmCancel() {
      var isCancel = confirm("Are you sure you wish to cancel?");
      if (isCancel) return true;
  
     return false;
  }  
    </script>
   
    <apex:form id="frm" >
       
        <apex:pageMessages id="showmsg"></apex:pageMessages>
        <apex:inputHidden value="{!targetField}" id="selectedAccId"/>
        <div style="background-color:#009EDB; border-radius:5px; padding:10px;" align="left">
            <b><apex:outputText value="Please Select Account" style="color:#FFFFFF; font-size:20px; font-family:calibri;"/></b>
        </div>
        
        <div align="left" style="padding:10px 5px 10px 5px; border:1px solid #ccc;">
            <apex:OutputLabel value="Account" style="color:#333;font-size:12px; font-weight:bold; padding-right:15px;" />
            <c:AutoCompleteV2 allowClear="true" importJquery="true" labelField="Name" id="acc" SObject="Account" valueField="Id" targetField="{!targetField}" style="width:200px"/>
        </div>
        
        <apex:repeat value="{!accountList}" var="acc" >
        </apex:repeat>
        
        <apex:commandButton id="con" value="Continue" action="{!Redirect}"  reRender="frm"  styleClass="ButtonStyle"  
                            style=" border:1px solid #cacaca; -webkit-border-radius: 4px; -moz-border-radius: 4px;border-radius: 4px;
                                   font-size:12px;font-family:arial, helvetica, sans-serif; margin-top:2px; padding:6px 8px 6px 8px; 
                                   text-decoration:none; font-weight:bold; color: #333;" />
        
        <apex:commandButton id="cancel" value="Cancel" action="{!Cancel}" styleClass="ButtonStyle" onclick="return confirmCancel()" immediate="true" style=" border:1px solid #cacaca; -webkit-border-radius: 3px; -moz-border-radius: 3px;border-radius: 3px;
                                                                                              font-size:12px;font-family:arial, helvetica, sans-serif; margin-top:2px; padding:6px 8px 6px 8px; 
                                                                                              text-decoration:none; font-weight:bold; color: #333;"   />
        
        <div style="padding:10px 8px 10px 8px;display:none" >
        </div>
        
    </apex:form>
    
</apex:page>


Autocompletev2_con
=================

public class AutoCompleteV2_Con {

    public String labelFieldVar{ get; set; }//for acc
    public String valueFieldVar{ get; set; }
    
    public String labelFieldSap{ get; set; }//for sap customer code
    public String valueFieldSapVar{ get; set; }
    
    public String sObjVal{get;set;}
    public Integer randomJsIden{get;set;}
    public Object cacheField{get;private set;} 
    
    private Object targetFieldVar;
    
    public AutoCompleteV2_Con(){
        randomJsIden = getRandomNumber(1000000);
        sObjVal='Account';
        labelFieldVar='Name';
        valueFieldVar='Id';
        labelFieldSap='SAP Customer Code';
        valueFieldSapVar='SAP_Customer_Code__c';
       // valueFieldOrgVar='';
    }
    
    /*Dummy setter Method*/
    public void setCacheField(Object cacheField){}
    
    public void setTargetFieldVar(Object targetFieldVar){    
        if(targetFieldVar != this.targetFieldVar){
            cacheField = getCacheFieldValue(targetFieldVar);
            this.targetFieldVar = targetFieldVar;
        }
    }
    
    public Object getTargetFieldVar(){
        return targetFieldVar;
    }

    
    /*
    *This method queries data according to the passed parameters
    ***/
    @RemoteAction
    public static List<Map<String,String>> getData(String sObjVal,String labelFieldVar,String labelFieldSap,String valueFieldVar,String valueFieldSapVar ,String whereClauseVar,String param){      
        List<Map<String,String>> responses = new List<Map<String,String>>();
        param = String.escapeSingleQuotes(param);
        for( Sobject sObj : Database.query('SELECT '+getFieldCSV(valueFieldVar,labelFieldVar)+''+getFieldCSV(valueFieldSapVar,labelFieldSap)+' FROM '+sObjVal+' WHERE '+labelFieldVar+''+labelFieldSap+' LIKE \'%'+param+'%\''+(String.isNotBlank(whereClauseVar) ? ' AND '+whereClauseVar : ''))){
            responses.add(new Map<String,String>{
                'id' => String.valueOf(sObj.get(valueFieldVar)),
                'text' => String.valueOf(sObj.get(labelFieldVar.split(',')[0])),
                'valueFieldSapVar' => String.valueOf(sObj.get(valueFieldSapVar)),
                'labelFieldSap' => String.valueOf(sObj.get(labelFieldSap))
            });
        }
        return responses;
    }  
    
    private Object getCacheFieldValue(Object targetFieldVar){
        Object retVal = targetFieldVar;
        if(targetFieldVar!=null){
            for(sObject sObj : Database.query('SELECT '+getFieldCSV(valueFieldVar,labelFieldVar)+''+getFieldCSV(valueFieldSapVar,labelFieldSap)+' FROM '+sObjVal+' WHERE '+valueFieldVar+''+valueFieldSapVar+' =:targetFieldVar')){
                retVal = sObj.get(labelFieldVar);
                break;
            }
        }
        
        return retVal;
    }
    
    /*
    *Random number generator to change the js function name if multiple components us
    ***/
    private Integer getRandomNumber(Integer size){
        Double d = Math.random() * size;
        return d.intValue();
    }

    private static String getFieldCSV(String vfld,String lfld){
        Set<String> fields = new Set<String>{vfld.toLowerCase(),lfld.toLowerCase()};
        return String.join(new List<String>(fields),',');
    }
    
}


Autocompletev2_con.vfp
=========================

<
<apex:component controller="AutoCompleteV2_Con" selfClosing="true">
    <apex:attribute name="SObject" description="SOQL Object to query"
        type="String" assignTo="{!sObjVal}" required="true" />
    <apex:attribute name="labelField"
        description="API Name of Field to display for label" type="String"
        required="true" assignTo="{!labelFieldVar}"/>
    <apex:attribute name="valueField"
        description="API Name of Field to display for value that is passed to the targetField"
        type="String" required="true" assignTo="{!valueFieldVar}"/>
    <apex:attribute name="targetField"
        description="Field of current object that will hold the selection."
        type="Object" assignTo="{!targetFieldVar}"/>
    <apex:attribute name="inputFieldId"
        description="Id of the field where the value will copied[Not generally required, used when you need to copy value to a field using js]"
        type="String" />
     <apex:attribute name="importJquery"
        description="Assign false if you dont want to jquery files"
        type="Boolean" default="true" />
    <apex:attribute name="syncManualEntry"
        description="Allow manual entry of data from autocomplete component."
        type="Boolean" default="true" />
    <apex:attribute name="allowClear" 
        description="Set true to give user a option to clear existing value" type="Boolean" default="true"/>
    <apex:attribute name="whereClause"
        description="Add where clause to the search"
        type="String" />
    <apex:attribute name="onChange"
        description="JS method to be invoked when the value changes"
        type="String" />
        
    <apex:attribute name="Style" description="style for the input component" type="String"/>
    <!--Required js files-->
    <apex:outputPanel rendered="{!importJquery}">
        <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"/>
    </apex:outputPanel>
        <apex:includeScript value="{!URLFOR($Resource.select2, 'select2-3.4.2/select2.js')}"/>
        <apex:stylesheet value="{!URLFOR($Resource.select2, 'select2-3.4.2/select2.css')}"/>
    <script>
        var v2{!randomJsIden};
        var prevVal{!randomJsIden};
        function autocompleteV2{!randomJsIden}(){
          var v2=this;
          jQuery(function($){
              v2.init($)
          });
        }
        
        autocompleteV2{!randomJsIden}.prototype={
          init : function($){
            var $elem = $( ".auto{!randomJsIden}" ).select2({
              minimumInputLength: 1,
              placeholder: "No value selected",
              allowClear : {!allowClear},
              query: function (query) {
                queryData{!randomJsIden}(query);
              },
              createSearchChoice:function(term, data) {
                if({!syncManualEntry} == true){
                  return {id:term, text:term};
                }
              }
            });

            $elem.on("select2-selecting", function(e) {
              $('.hiddenField{!randomJsIden}').val(e.val);
            });

            $elem.on("select2-removed", function(e) {
              $('.hiddenField{!randomJsIden}').val('');
            });

            if({!NOT(ISNULL(onChange))}){
                $elem.on("select2-selecting",{!IF(ISNULL(onChange), 'function(e){}',onChange)});
            }

            if({!cacheField !=''}){
              $elem.select2("data", {id: "{!targetFieldVar}", text: "{!cacheField}"})  
            }  
          },
                    
          triggerSearch :function(val){
            if(prevVal{!randomJsIden} != val){
              $=jQuery;
              prevVal{!randomJsIden} = val;
              var select = $('input.auto{!randomJsIden}');          
              var search = $('.select2-input')
              select.select2('open');
              search.val(val);
              search.trigger("input");
            }
          }
        }

         /*
        *This method queries data according to the passed parameter
        *and populates the combobox accordingly
        ***/    
        function queryData{!randomJsIden}(query){
          Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.AutoCompleteV2_Con.getData}','{!sObjVal}','{!labelFieldSap}','{!labelFieldVar}','{!valueFieldVar}','{!valueFieldSapVar}',"{!whereClause}",query.term,
            function(result, event){
              //if success
              if(event.status){ 
                var data = {results: []}
                data.results = result;                            
                query.callback( data);                           
              }
              else{
                alert('Invalid Field/Object API Name : '+event.message);
              }
            }, 
            {escape: false}
          );
        }         
    </script>
    
    <apex:inputText style="{!Style}" styleClass="auto{!randomJsIden}" value="{!cacheField}" />
 
    <apex:outputPanel id="hiddenPanel">
        <apex:inputText value="{!targetField}" id="hiddenField"
            styleClass="hiddenField{!randomJsIden}" style="display:none"/>
    </apex:outputPanel>
    <script>v2{!randomJsIden} = new autocompleteV2{!randomJsIden}({});</script>
</apex:component>
ShirishaShirisha (Salesforce Developers) 
Hi Ashish,

Greetings!

Are you observing any errors while working with the visualforce pages.I would suggest you to add debug statements to troubleshoot the code.

Kindly mark it as best answer if it helps so that it can help others in the future.

Warm Regards,
Shirisha Pathuri