custom lookup

Custom Lookup Field in Visualforce Page | Salesforce Developer Guide

We all know about the Standard Lookup functionality, it's provided by Salesforce. The standard Lookup field gives a dialog box that supports a little quantity of customization. If you want the results ordered and filtered then you have to enable the Enhanced lookup. So if you want to create a VF page with a standard controller, you can easily create a standard lookup field.

Here we can discuss the Custom Lookup Field is a Visualforce Page:

If you want to create a VF page with a custom controller then you have to create a custom lookup field. In this scenario, first, you have to create a VF page for lookup.

Let’s take an example for a better understanding of it.

In this example, we can create a VF page and on this page, we can use the custom lookup field.

dont miss out iconDon't forget to check out: 4 Reasons to use AngularJS in Salesforce Visualforce pages

Controller: 

Let’s first create a Controller for the VF page and named as CustomLookupController.apxc

public with sharing class CustomLookupController {
    public String query {get; set;}
    public List<Account> accounts {get; set;}
    public Boolean doneLookup {get; set;}    
    // constructor
    public LookupController() {
    	doneLookup=false;
    }
    // executes the search
    public PageReference runQuery() {
        List<List<Account>> searchResults=
            [FIND :query IN ALL FIELDS RETURNING 
                Account (id, name, billingstreet, billingcity, billingpostalcode)];
        accounts=searchResults[0];
        doneLookup=true;
        return null;
    }
}

Main Visualforce Page:

Now, create a VF page to show the lookup details. And it's named as LookupPopup.vfp

<apex:page controller="CustomLookupController " sidebar="false" showheader="false" standardstylesheets="true">
<head>
    <title>Custom Lookup</title>
</head>
  <apex:messages />
  <apex:form id="form" >  
     <div style="width 90%; margin-left:10px">
        <div style='text-align:center; font-size:20px; font-weight:bold'>Lookup</div>
        <p>Please enter the search term below and click the 'Go' button.  This will
           execute a search across all text fields</p>
        <p><span style="color:red">IMPORTANT: </span>Please ensure you enter at least two characters</p>
        <hr/>
        <span><apex:inputText value="{!query}" id="query"/></span> 
        <span><apex:commandButton value="Go" action="{!runQuery}"/></span>        
        <apex:pageBlock mode="mainDetail" rendered="{!doneLookup}">
          <apex:pageBlockButtons location="bottom">
            <apex:commandButton value="Close Window" onclick="CloseWindow(); return false;" />
          </apex:pageBlockButtons>
          <apex:pageBlockSection columns="1">
              <apex:pageBlockTable value="{!accounts}" var="account">
                <apex:column headerValue="Name">
                  <apex:outputLink value="#" onclick="fillIn('{!account.Name}', '{!account.id}')">{!account.Name}</apex:outputLink>       
                </apex:column>
                <apex:column headerValue="Street" value="{!account.BillingStreet}"/>
                <apex:column headerValue="City" value="{!account.BillingCity}"/>
                <apex:column headerValue="Postcode" value="{!account.BillingPostalCode}"/>
              </apex:pageBlockTable>    
          </apex:pageBlockSection>
        </apex:pageBlock>
     </div>
   </apex:form>
   <script language="javascript">
   window.onload = new function() 
   { 
      // bring popup window to front
      window.focus(); 
      var ele=document.getElementById('{!$Component.form.block.section.query}');
      if (ele)
      {
         ele.focus();
      }
   }   
   function fillIn(name, id)
   {
      var winMain=window.opener;
      if (null==winMain)
      {
         winMain=window.parent.opener;
      }
      var ele=winMain.document.getElementById('{!$CurrentPage.parameters.namefield}');
      ele.value=name;
      ele=winMain.document.getElementById('{!$CurrentPage.parameters.idfield}');
      ele.value=id;
      winMain.closeLookupPopup();
   }
   </script>   
</apex:page>

Lookup Visualforce Page:

Finally, Create a VF page named Lookup.vfp

<apex:page standardController="Opportunity">
  <apex:form >
    <apex:pageBlock mode="mainDetail" title="Create Opportunity">
      <apex:pageBlockButtons >
        <apex:commandButton value="Save" action="{!save}" />
        <apex:commandButton value="Cancel" action="{!cancel}" />
      </apex:pageBlockButtons>
      <apex:pageBlockSection title="Detail">
        <apex:inputField value="{!Opportunity.Name}" />
        <apex:inputField value="{!Opportunity.CloseDate}"/>
        <apex:inputField value="{!Opportunity.Amount}" />
        <apex:inputField value="{!Opportunity.StageName}" />
        <apex:pageBlockSectionitem >
          <apex:outputLabel value="Account"/>
          <apex:outputPanel layout="inline" style="vertical-align:middle">
  	        <apex:inputHidden value="{!Opportunity.AccountId}" id="targetId" />
            <apex:inputText size="20" id="targetName" onFocus="this.blur()"/>
            <a href="#" onclick="openLookupPopup('{!$Component.targetName}', '{!$Component.targetId}'); return false"><apex:image style="vertical-align:middle;width:21px; height:21px" value="/img/icon/telescope16.png" /></a>
          </apex:outputPanel>
        </apex:pageBlockSectionitem>
      </apex:pageBlockSection>
    </apex:pageBlock>
  </apex:form>
  <script>
    var newWin=null;
    function openLookupPopup(name, id)
    {
        var url="/apex/LookupPopup?namefield=" + name + "&idfield=" + id;
        newWin=window.open(url, 'Popup','height=500,width=600,left=100,top=100,resizable=no,scrollbars=yes,toolbar=no,status=no');
        if (window.focus) 
        {
            newWin.focus();
        }            
        return false;
    }                  
    function closeLookupPopup()
    {
       if (null!=newWin)
       {
          newWin.close();
       }  
    }
  </script>
</apex:page>

dont miss out iconCheck out another amazing blog by Shweta here: How Does a Post Install Script Work? - Salesforce Developer Guide

Output:

When you can Click on the telescope button to the right of the accounts field it opens the popup window. And this lookup window contains the account id of the selected account. 

Responses

  1. Hi. I am this code so thank you so much for this! But I would like to ask a question, when I'm doing this, my lookup field (which is an inputtext) is not firing an onchange actionsupport. I read that it is because actionsupport is not supporting Javascript update. Do you know any workaround?

Popular Salesforce Blogs