Skip to main content

Customize Salesforce Lookup with Visualforce

This code is inspired from ROLL YOUR OWN SALESFORCE "LOOKUP" POPUP WINDOW . I did a little bit customization and save it here for reference purpose.

The scenario, I have Account Plan for every Account  and this Account Plan will have many Roles.It 's similar to Opportunity and Opportunity Contact Role relationship.In this case we want to filter Role to only retrieve the Contact from the related Account.Role has master detail relationship with Account Plan.

I have tried Lookup filter but it does not work.Also I want to customize layout in the lookup page.I got the code from Jeff Douglas's blog and remove the tab.In the code example, it only referring to one input value but I got multiple input value that generated by apex:repeat like below.

When user click on the icon, it will bring them to this page .Please note that I added Job Title, Department and also it will limit the search Contact on to related Account.
Here is the file structure :
  1. Your existing Visualforce page where you have the inputfield that will call the popup
  2. Visualforce page for Lookup page
  3. Apex controller for Lookup page

First we start with Lookup page.I added extra column for Job Title and Department

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<apex:page controller="Lookup_Controller"
  title="Search" 
  showHeader="false" 
  sideBar="false" 
  tabStyle="Contact" 
  id="pg">
  
  <apex:form >
  <apex:outputPanel id="page" layout="block" style="margin:5px;padding:10px;padding-top:2px;">
               <apex:actionRegion >  
                  <apex:outputPanel id="top" layout="block" style="margin:5px;padding:10px;padding-top:2px;">
                    <apex:outputLabel value="Search" style="font-weight:Bold;padding-right:10px;" for="txtSearch"/>
                    <apex:inputText id="txtSearch" value="{!searchString}" />
                      <span style="padding-left:5px"><apex:commandButton id="btnGo" value="Go" action="{!Search}" rerender="searchResults"></apex:commandButton></span>
                  </apex:outputPanel>
       
                <apex:outputPanel id="pnlSearchResults" style="margin:10px;height:350px;overflow-Y:auto;" layout="block">
                    <apex:pageBlock id="searchResults"> 
                      <apex:pageBlockTable value="{!results}" var="a" id="tblResults">
                        <apex:column >
                          <apex:facet name="header">
                            <apex:outputPanel >Name</apex:outputPanel>
                          </apex:facet>
                           <apex:outputLink value="javascript:top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.Id}','{!a.Name}', false)" rendered="{!NOT(ISNULL(a.Id))}">{!a.Name}</apex:outputLink>                          
                          </apex:column>
                         <apex:column value="{!a.Title}"/>
                          <apex:column value="{!a.Department}"/>

                      </apex:pageBlockTable>
                    </apex:pageBlock>
                </apex:outputPanel>
            </apex:actionRegion>
              
       
  </apex:outputPanel>
  </apex:form>
</apex:page>

Now we add the controller class.Note that I add accountId to filter Contact for related Account.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public with sharing class Lookup_Controller {
  public List<Contact> results{get;set;} // search results
  public string searchString{get;set;} // search keyword
  public String accountId {get;set;} //accound id that passed
  
  public Lookup_Controller () {
    searchString = System.currentPageReference().getParameters().get('lksrch');
    //retrieve accountId
 accountId=System.currentPageReference().getParameters().get('accountId');
    
    runSearch();  
  }
   
  // performs the keyword search
  public PageReference search() {
    runSearch();
    return null;
  }
  
  // prepare the query and issue the search command
  private void runSearch() {
     results = performSearch(searchString);               
  } 
  
  // run the search and return the records found. 
  private List<Contact> performSearch(string searchString) {
    String soql = 'select id, name,title,department from Contact Where  AccountId =\''+String.escapeSingleQuotes(accountId)+'\'';
    if(searchString != '' && searchString != null)
      soql = soql +  ' and name LIKE \'%' + String.escapeSingleQuotes(searchString) +'%\'' ;
    soql = soql + ' limit 25';
    System.debug(soql);
    return database.query(soql); 

  }
  
  
  // used by the visualforce page to send the link to the right dom element
  public string getFormTag() {
    return System.currentPageReference().getParameters().get('frm');
  }
    
  // used by the visualforce page to send the link to the right dom element for the text box
  public string getTextBox() {
    return System.currentPageReference().getParameters().get('txt');
  }
 

}

Now this is the page that you call the Lookup page.Please focus on the form and input id and openLookup function.I call Lookup_VF and pass accountId in the function.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<apex:page standardController="Account_Plan__c"  title="Account Plan Contact Role" >
<script type="text/javascript">
    
   function openLookup(baseURL, width, modified, searchParam){
    var originalbaseURL = baseURL;
    var originalwidth = width;
    var originalmodified = modified;
    var originalsearchParam = searchParam;
    
    var lookupType = baseURL.substr(baseURL.length-3, 3);
    if (modified == '1') baseURL = baseURL + searchParam;
    
    var isCustomLookup = false;
    
    // Following "001" is the lookup type for Account object so change this as per your standard or custom object
    if(lookupType == "003"){
  
      var urlArr = baseURL.split("&");
      var txtId = '';
      if(urlArr.length > 2) {
        urlArr = urlArr[1].split('=');
        txtId = urlArr[1];
      }
      
      // Following is the url of Custom Lookup page. You need to change that accordingly
      baseURL = "/apex/Lookup_VF?txt=" + txtId+"&accountId="+'{!Account_Plan__c.Account__c}';
      
      // Following is the id of apex:form control "myForm". You need to change that accordingly
      baseURL = baseURL + "&frm=" + escapeUTF("{!$Component.contactForm}");
      if (modified == '1') {
        baseURL = baseURL + "&lksearch=" + searchParam;
      }
      console.log('txtId =='+txtId);
      // Following is the ID of inputField that is the lookup to be customized as custom lookup
      if(txtId.indexOf('contactName') > -1 ){
        isCustomLookup = true;
      }
    }
    
    
    if(isCustomLookup == true){
      openPopup(baseURL, "lookup", 350, 480, "width="+width+",height=480,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollable=no", true);
    }
    else {
      if (modified == '1') originalbaseURL = originalbaseURL + originalsearchParam;
      openPopup(originalbaseURL, "lookup", 350, 480, "width="+originalwidth+",height=480,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollable=no", true);
    } 
  }
    
</script>

<apex:form id="contactForm">

<apex:pageBlock title="Account Plan Contact Role" >

<apex:pageBlockTable value="{!listRoleObject}" var="roles" border="0" id="contactRoleTable">
<apex:column >
 <apex:facet name="header">Name</apex:facet>
  <apex:inputField value="{!roles.contactRole.Contact__c}" id="contactName" rendered="{!roles.paramId!='None'}"/><apex:outputText value="No Primary Contact" rendered="{!roles.paramId=='None'}"></apex:outputText>
</apex:column>
<apex:column >
 <apex:facet name="header">Role</apex:facet>
<apex:inputField value="{!roles.contactRole.Role__c}"  rendered="{!roles.paramId!='None'}" id="roleInput" required="{!roles.isChecked}"/>
</apex:column>

</apex:pageBlockTable>

<apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Save" />    <apex:commandButton action="{!cancel}" value="Cancel"/>
            </apex:pageBlockButtons>

</apex:pageBlock>
</apex:form>
</apex:page>
I hope this help.Happy Friday =)

Comments

Post a Comment

Popular posts from this blog

Search Solution Basics

When is it a good time to create a customized search solution? You're developing an external knowledge base for user support. You're in the mood for a fun Friday night. The sales reps just started using the Sales Cloud in Lightning Experience. You want to put your company branding in the search bar. What differentiates SOSL from SOQL? Syntax SOSL searches the search index instead of the org database. SOSL searches more efficiently when you don't know in which object the data resides. All of the above. SOSL works with: REST only SOAP only REST, SOAP, and Apex SOQL only What does a search for a single object look like in SOSL? FIND {cloud} RETURNING Account FIND in ACCOUNT RETURNING "cloud" FIND "cloud" in ACCOUNT FIND (cloud) RIGHT NOW! What does a search for multiple objects look like in SOSL? FIND {sneakers} RETURNING ALL ARTICLES FIND {sneakers} in ALL OBJECTS FIND {sneakers} RETURNING Product2, Content

Process Builder is not fired when field update is called from Approval Process

Scenario In Final Approvals section ; in Approval Process we have field update to update Status field. In Process Builder , we have some action that need to be done when Status field is updated in Approval Process.However this process builder is not fired. Solution To handle this, in Field Update in Approval Process , check Re-evaluated Workflow Rules after Field Change as picture below. What happen if field updated from Approval Process. Workflow - does not fires untill Re-evaluate workflow checkbox is ticked on your field update Process Builder - does not fires untill Re-evaluate workflow checkbox is ticked on your field update Trigger - will fire if conditions are matched This is explained in article here  . Field Updates That Re-evaluate Workflow Rules If  Re-evaluate Workflow Rules After Field Change  is enabled for a field update action, Salesforce  re-evaluates all workflow rules on the object if the field update results in a change to the value of the fi

Tips and Tricks : Test class for Invocable method

Issue : I got 100% coverage in my sandbox but when run validation for deployment it returns 0% coverage It turn out that in my sandbox, I am depending on Process Builder to Invocable Apex class, as long I manipulate test data that fire Process Builder it will call Invocable class. This is not useful when deploying it to Production although it gets deployed together with Process Builder. The correct way is to direct call Invocable method inside test class itself. Example of class : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 global class MyCustomObject_StatusUpdate_Util { @InvocableMethod ( label = ' Update Quote Status ' ) public static void updateQuote ( Request [] requests ) { Set < Id > setOppId = new Set < Id >(); List < SBQQ__Quote__c > listQuoteToUpdate = new List < SBQQ__Quote__c >(); for ( Request request : requests ) {