Friday, March 31, 2017

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 =)

No comments:

Post a Comment