Saturday, 6 June 2015

Predicting look up field For Visualforce


         Here is a simple code for creating a lookup field in Visualforce  that allows a user to select the desired lookup object from a list that is predicted by this code. Generally it dose the same thing as the standard search and select window that appears for a lookup but in style. It is a simple code and i know there are huge scopes for optimization and improvement as this is an idea(and they are bullet proof).Feel free to suggest any improvement you come by.


The Code

             The code here simply renders to a page displaying the available contracts and provides a panel to create new ones. The account field is designed to be a what i call predicting lookup field.

Visualforce
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
 function genlist()
        {   
            var original= $(this).val();
            
            if(original.length>0)
            {
            $(".drpdwnlist").show();
            LookupTestController.accsearch(original,function(result){
            var row = result.split('#');var projected='';
            
            for(var i=0;i<row.length-1;i++)
            {
              var field = row[i].split('%');
              
                 projected+='<div style="width:175px;" onClick="selectit.call($(this))" class="option" data-iden='+field[1]+'>'+field[0]+'</div>';
             
                
            }
            
            $('.drpdwnlist').html(projected);
            });
            }
            else
            {
            $(this).closest('span').next().hide();
            }
        }
        function selectit()
        {
         var a = $(this).text();
         var b = $(this).attr("data-iden");
         $(this).parent().prev().val(b);
         $(this).parent().prev().prev().val(a);
         $('.drpdwnlist').hide();
         $('.accdrpdwnlist').hide();
                 
        }

</script>

 <apex:messages />
 <apex:form >
 <apex:pageBlock title="Create Contract">
 <apex:pageBlockSection >
     
     <apex:inputField value="{!con.Description}"/>
     <apex:inputField value="{!con.StartDate}"/>
     <apex:inputField value="{!con.ContractTerm}"/>
     <apex:outputPanel >
                        <apex:outputText ><b>Related Account</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</apex:outputText>
                        <apex:inputText value="{!con.Account.name}" onkeypress="genlist.call($(this));" required="true" styleClass="inpacc"/>
                        <apex:inputText value="{!Acclookup}" styleClass="dummy"/>
                        <div class="drpdwnlist"></div>
     </apex:outputPanel>
     
 </apex:pageBlockSection>
 <centre><apex:commandButton Action="{!saveit}" value="Save"/></centre>
 </apex:pageBlock>
 <apex:pageBlock >
 <apex:pageBlockTable var="contra" value="{!Conlist}">

 <apex:column value="{!contra.Account.name}"/>
 <apex:column value="{!contra.ContractTerm}"/>
 <apex:column value="{!contra.StartDate}"/>
 <apex:column value="{!contra.Description}"/>
 </apex:pageBlockTable>
 </apex:pageBlock>
 </apex:form>
 <style>
 .dummy
{
              display : none;
}
.drpdwnlist
 {
              position:relative;
              margin-left:17%;
              <!--margin-left:110px;-->
              background-color:#E6E6E6;
             -webkit-box-shadow: 1px 3px 39px -6px rgba(133,124,133,1);
             -moz-box-shadow: 1px 3px 39px -6px rgba(133,124,133,1);
              box-shadow: 1px 3px 39px -6px rgba(133,124,133,1);
              display:none;
              width:174px;
              Height:100px;
              overflow:scroll;
             
 }
 .option:hover
 {
             background-color:#99CCFF;
             cursor:pointer;
 }
 </style>

Controller

public class LookupTestController {

public contract con{get;set;}
Public String Acclookup{get;set;}
public List<Contract> Conlist{get;set;}

public LookupTestController ()
{
         con = new contract();     
         con.status = 'Draft';
         Conlist = [select Account.name,Owner.Name,ContractTerm,StartDate,Description from contract];
}

 @RemoteAction public static string accsearch(string sample)
    {
       string qstring = '%'+sample+'%';
       string resultstring='';
       list<Account> srchacclist = [select id,name from Account where name like:qstring];
      
       for(Account a : srchacclist)
             resultstring+=a.name+'%'+a.id+'#';
      
       return resultstring;
    }

public Void Saveit()
{
   con.AccountId = Acclookup;
   try{
   insert con;
   }
   catch(exception c)
   {
     Apexpages.addMessage(new Apexpages.Message(ApexPages.Severity.Info,c.getMessage()));
   }
}


}

Demo

Click for Demo


How it Works
   
       Whenever a text is inserted in the input box the java script function is called (genlist()) and the java script then fires a remote method on the controller (accsearch( string)) with the value from the text field and the function then returns the name and ids of the accounts as a string(Yes sir that can be a json). Then the java script decomposes the returned string and displays as the list.

When ever a click is done on an item on the list Jquery puts the name of the account on the input text box and there is another hidden input text box which gets the id of the selected item(in this case a account id). The id is then fed to the lookup field of the object in controller.

Note:if you can't understand this code (That's entirely my fault because i cant express you the thing) just send me a mail on tanumay.das@gmail.com