function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
justinhowell82justinhowell82 

override openLookup inside apex component

I follwoed the instructions found here:  http://blog.jeffdouglas.com/2011/08/12/roll-your-own-salesforce-lookup-popup-window/  which are pretty straight forward to try to override the standard lookup functionality.  I implemented this within my apex component and it is never getting inside the function openLookup that I have defined within my component.  Is there anything that would need ot be done differently when called from a component vs a VF page?
Best Answer chosen by justinhowell82
logontokartiklogontokartik
Sorry here is the component
<pre>
<apex:component controller="MyCustomLookupController" allowDML="true">

  <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);
        //var lookupType = baseURL.substr(baseURL.indexOf(‘lktp’)+5, 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 == "001"){

      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/CustomAccountLookup?txt=" + txtId;

      // Following is the id of apex:form control "myForm". You need to change that accordingly
      baseURL = baseURL + "&frm=" + escapeUTF("{!$Component.myForm}");
      if (modified == '1') {
       baseURL = baseURL + "&lksearch=" + searchParam;
       //baseURL = baseURL + searchParam
      }

      // Following is the ID of inputField that is the lookup to be customized as custom lookup
      if(txtId.indexOf('Vendor') > -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:sectionHeader title="Demo"  subtitle="Custom Lookup" />

<apex:form id="myForm" >
<!--<apex:outputLabel value="{!QID}" />-->

     <apex:pageBlock id="AdjustQuoteLines">
        <apex:inputField ID="Vendor" value="{!contact.AccountId}"  />
 
  </apex:PageBlock>
</apex:form>
</apex:component>
</pre>

All Answers

logontokartiklogontokartik
can you paste your code so that I can see where the issue is?
justinhowell82justinhowell82
Component Code:

<apex:component id="QuoteLinesComponent" controller="QuoteLinewrapperClassController" allowDml="true" >

<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);
    var lookupType = baseURL.substr(baseURL.indexOf(‘lktp’)+5, 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 == "001"){

      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/QuoteVendorLookup?txt=" + txtId;

      // Following is the id of apex:form control "myForm". You need to change that accordingly
      baseURL = baseURL + "&frm=" + escapeUTF("{!$Component.myForm}");
      if (modified == '1') {
       baseURL = baseURL + "&lksearch=" + searchParam;
       //baseURL = baseURL + searchParam
      }

      // Following is the ID of inputField that is the lookup to be customized as custom lookup
      if(txtId.indexOf('Vendor') > -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);    }
  }
   

   


<apex:form id="myForm" >
<!--<apex:outputLabel value="{!QID}" />-->

     <apex:pageBlock id="AdjustQuoteLines" >

                   <apex:inputField ID="Vendor" value="{!contact.AccountId}"/>
justinhowell82justinhowell82
controller code:

public class QuoteLinewrapperClassController {

public QuoteLinewrapperClassController(){
    
       QuoteLinesList = null;
       contact = new Contact();
    
     
    }

public Contact contact {get;set;}



}

logontokartiklogontokartik
Briefly looking at your code, it seems like below is causing the issue. uncomment the top one and comment the 2nd line and see if it works.
<pre>
//var lookupType = baseURL.substr(baseURL.length-3, 3);
    var lookupType = baseURL.substr(baseURL.indexOf(‘lktp’)+5, 3);
</pre>
justinhowell82justinhowell82
I had it that way originally and it did not work.  It does not even seem as if it is getting inside my javascript function.  I don't really know the best bay to debug this to determine if it is getting into my js.  I tried modifying some of the code in that function and the standard lookup window continues to be displayed.

Thanks,
Justin
logontokartiklogontokartik
If you are using chrome, you can basically use the Chrome Developer Tools (option+command+i in mac, or rightclick and click inspect element.). to see if there are any errors in the JS. You can add console.log statements in the Javascript as well
justinhowell82justinhowell82
I have tried adding console.log statements and alerts to the javascript before any other processing happens and they are never called.
justinhowell82justinhowell82
here is the code generated for the lookup inputfield:

<span class="lookupInput">
<input id="j_id0:QuoteLinesComponent:QuoteLinesComponent:myForm:AdjustQuoteLines:Vendor" maxlength="255" name="j_id0:QuoteLinesComponent:QuoteLinesComponent:myForm:AdjustQuoteLines:Vendor" onchange="getElementByIdCS('j_id0:QuoteLinesComponent:QuoteLinesComponent:myForm:AdjustQuoteLines:Vendor_lkid').value='';getElementByIdCS('j_id0:QuoteLinesComponent:QuoteLinesComponent:myForm:AdjustQuoteLines:Vendor_mod').value='1';" size="20" type="text">

<script>new ForeignKeyInputElement("j_id0:QuoteLinesComponent:QuoteLinesComponent:myForm:AdjustQuoteLines:Vendor","/_ui/common/data/LookupValidationServlet",null,true,{"acent":"001"});</script>

<a href="javascript:%20openLookup%28%27%2F_ui%2Fcommon%2Fdata%2FLookupPage%3Flkfm%3Dj_id0%253AQuoteLinesComponent%253AQuoteLinesComponent%253AmyForm%26lknm%3Dj_id0%253AQuoteLinesComponent%253AQuoteLinesComponent%253AmyForm%253AAdjustQuoteLines%253AVendor%26lktp%3D%27%20%2B%20getElementByIdCS%28%27j_id0%3AQuoteLinesComponent%3AQuoteLinesComponent%3AmyForm%3AAdjustQuoteLines%3AVendor_lktp%27%29.value%2C670%2C%271%27%2C%27%26lksrch%3D%27%20%2B%20escapeUTF%28getElementByIdCS%28%27j_id0%3AQuoteLinesComponent%3AQuoteLinesComponent%3AmyForm%3AAdjustQuoteLines%3AVendor%27%29.value.substring%280%2C%2080%29%29%29" id="j_id0:QuoteLinesComponent:QuoteLinesComponent:myForm:AdjustQuoteLines:Vendor_lkwgt" onclick="setLastMousePosition(event)" title="Account Name/Sub-Agency Lookup (New Window)"><img src="/s.gif" alt="Account Name/Sub-Agency Lookup (New Window)" class="lookupIcon" onblur="this.className = 'lookupIcon';" onfocus="this.className = 'lookupIconOn';" onmouseout="this.className = 'lookupIcon';this.className = 'lookupIcon';" onmouseover="this.className = 'lookupIconOn';this.className = 'lookupIconOn';" title="Account Name/Sub-Agency Lookup (New Window)"></a></span>

justinhowell82justinhowell82
It looks like the link for ht elookup icon should call the openLookup js function.  But it is not calling hte one I have defined on the page becuase there are no log statements, alerts being shown, or errors.
logontokartiklogontokartik
I copied your component and it worked for me.

<pre>
<apex:page controller="CustomAccountLookupController"
  title="Search"
  showHeader="false"
  sideBar="false"
  tabStyle="Account"
  id="pg">
 
  <apex:form >
  <apex:outputPanel id="page" layout="block" style="margin:5px;padding:10px;padding-top:2px;">
  <apex:tabPanel switchType="client" selectedTab="name1" id="tabbedPanel">
 
    <!-- SEARCH TAB -->
      <apex:tab label="Search" name="tab1" id="tabOne">
       
      <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:pageBlockTable>
        </apex:pageBlock>
       </apex:outputPanel>
      </apex:actionRegion>
       
    </apex:tab>
   
    <!-- NEW ACCOUNT TAB -->
    <apex:tab label="New Account" name="tab2" id="tabTwo">

        <apex:pageBlock id="newAccount" title="New Account" >
       
          <apex:pageBlockButtons >
            <apex:commandButton action="{!saveAccount}" value="Save"/>
          </apex:pageBlockButtons>
          <apex:pageMessages />
       
          <apex:pageBlockSection columns="2">
           
              <apex:inputField value="{!Account.Name}"/>
           
          </apex:pageBlockSection>
        </apex:pageBlock>
       
    </apex:tab>
  </apex:tabPanel>
  </apex:outputPanel>
  </apex:form>
</apex:page>
</pre>
logontokartiklogontokartik
Visualforce page is
<pre>
<apex:page id="Page" tabstyle="Contact">

    <c:CustomLookupComp />
      
</apex:page>

</pre>
justinhowell82justinhowell82
I do not see your code for the compopnent that is on the VF page.   The page CustomAccountLookupController is the page that should appear instead of the standard sf lookup page correct?
logontokartiklogontokartik
Sorry here is the component
<pre>
<apex:component controller="MyCustomLookupController" allowDML="true">

  <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);
        //var lookupType = baseURL.substr(baseURL.indexOf(‘lktp’)+5, 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 == "001"){

      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/CustomAccountLookup?txt=" + txtId;

      // Following is the id of apex:form control "myForm". You need to change that accordingly
      baseURL = baseURL + "&frm=" + escapeUTF("{!$Component.myForm}");
      if (modified == '1') {
       baseURL = baseURL + "&lksearch=" + searchParam;
       //baseURL = baseURL + searchParam
      }

      // Following is the ID of inputField that is the lookup to be customized as custom lookup
      if(txtId.indexOf('Vendor') > -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:sectionHeader title="Demo"  subtitle="Custom Lookup" />

<apex:form id="myForm" >
<!--<apex:outputLabel value="{!QID}" />-->

     <apex:pageBlock id="AdjustQuoteLines">
        <apex:inputField ID="Vendor" value="{!contact.AccountId}"  />
 
  </apex:PageBlock>
</apex:form>
</apex:component>
</pre>
This was selected as the best answer
justinhowell82justinhowell82
hmm....I really appreciate your help.  It seems we have the exact same code but it is not working for me.  I'm really not sure what else to try other than stripping the functionality out of the component and throwing it on a page just to see if I can get it to work??
justinhowell82justinhowell82
well, you saved my day!!   I still don't know what the issue was since I was getting no errors and no logs but I started over with a new component and page and it seems to work fine now.  I do get a completely different error in the new search page "Error: Unknown property 'Account.fieldsets.CustomAccountLookup'", but for right now I'm going to comment out the add new section as it is not needed right now.   If you ahve any quick solutions to that I would appreciate.
logontokartiklogontokartik
Yes. I think Jeff was using a fieldset to iterate over the Account Fields when trying to create a new Account. You can take that repeat part and manually add in the required fields (for account Name should be sufficient)
haripriya.maturiharipriya.maturi
Hi logontokartik,

I have implemented openLookup(baseURL, width, modified, searchParam) to override the lookup popup window in my VisualforcePage, its working fine, but it will not working in Detail view page (I am using <apex:detail> in my VF page), as there will not available ID for the lookup field.  Can you suggest me how to achive this in Detail view page also.

Thanks,
Haripriya


Олег СавинковОлег Савинков
I have used this code. It work fine when i editing some records, but i have error, when  i insert new record.
This is my VF page, that  inserting new object:
<apex:page standardController="CallReportHosp__c" extensions="CtrlCallHospInsert" id="CallsHospInsert">
 <apex:form id="myForm">
  

<script>
window.addSelectedOrganisations = function(Organisations) {
            applyFilterByOrganisations(Organisations);}
</script>

<script>
                        

 if(window.attachEvent)

        window.attachEvent('onload',getV())

     else if(window.addEventListener)

        window.addEventListener('load',getV(),false)

   
                            function getV() {

                            var AccValue = document.getElementById("CallsHospInsert:myForm:pblock:pBS:pBSI:organisation").value;
                            document.getElementById("CallsHospInsert:myForm:pblock:theHiddenInput").value=AccValue;
                            console.log('getv '+AccValue);
//                            console.log('id= '+id);
                            
                            myFun(AccValue); 

                                                                       
                        }
                    </script>

<script>     
 function openLookup(BaseUrl,width,modified,searchstr)
        {
           var receivedUrl=BaseUrl;
           var receivedwidth=width;
           var receivedmodified=modified;
           var receivedsearchstr=searchstr;
           var lookuptype=receivedUrl.substr(receivedUrl.length-3,3);
           if(receivedmodified=='1')
           {
               BaseUrl=BaseUrl+searchstr;
           }
           var urlArr=BaseUrl.split("&");
               //----If you are using this in inline editing then it would be var NxtSpltArr=urlArr[0].split("="); -----------
               var NxtSpltArr=urlArr[1].split("=");
               var txtfrmarr=NxtSpltArr[1];
           if(lookuptype=='001')
           {
             
           if(txtfrmarr.indexOf('organisation')> -1)
               {

                   BaseUrl="/apex/AccountsListforHosp?context=pharma_chain&list=noList&txt="+txtfrmarr;
                   BaseUrl=BaseUrl + "&frm=" + escapeUTF("{!$Component.myForm}");
                   BaseUrl=BaseUrl + "&lksearch=" + searchstr;
               }
           
               
           }
            if(lookuptype=='003')
           {
              
           
           if(txtfrmarr.indexOf('contact')> -1)
               {   
                   var orgid = document.getElementById("CallsHospInsert:myForm:pblock:theHiddenInput").value;
                   BaseUrl="/apex/ContactsListforHosp?context=pharma_chain&list=noList&org="+orgid+"&txt="+txtfrmarr;
                   BaseUrl=BaseUrl + "&frm=" + escapeUTF("{!$Component.myForm}");
                   BaseUrl=BaseUrl + "&lksearch=" + searchstr;
                   console.log('id= '+orgid);
               }               
           }
           openPopup(BaseUrl,"lookup",950,480,"width=1420,height=480,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollable=no",true);   

        }
</script>

 <apex:actionfunction name="applyFilterByOrganisations" action="{!applyFilterByOrganisations}" rerender="organisation" status="asLoadingSelectedOrganisations">
            <apex:param name="selectedOrganisationsStr" value="" assignto="{!selectedOrganisationsStr}" />
        </apex:actionfunction>
                    
<apex:actionfunction name="myFun" action="{!SelectServiceIns}"  reRender="contactPanel,address,theHiddenInput,organisation" immediate="true">
<apex:param name="AccIns" value="" assignTo="{!AccIns}"/>
  
</apex:actionFunction>            
            
            
        <apex:pageBlock mode="edit" id="pblock" >
            <apex:pageMessages id="message" />
            <apex:pageBlockButtons location="top">                                
                <apex:actionStatus id="mySaveStatus1">
                <apex:facet name="stop">
                <apex:commandButton value="Save" action="{!save}" rerender="pblock" status="mySaveStatus1"/>
                </apex:facet>
                <apex:facet name="start">
                <apex:commandButton value="Save" status="mySaveStatus1" disabled="true"/>
                </apex:facet>
                </apex:actionStatus>
                <apex:commandButton value="Cancel" action="{!cancel}"/>
            </apex:pageBlockButtons>
            
   <apex:inputHidden value="{!AccIns}" id="theHiddenInput" />    
      

             
<!--            <apex:outputPanel rendered="{!IF($CurrentPage.parameters.theType = 'app', false, true)}" >-->
            <apex:pageBlockSection columns="2" id="pBS">
                <apex:pageBlockSectionItem id="pBSI">                
                    <apex:outputLabel value="Organisation" for="organisation"/>
                    <apex:inputfield value="{!rep.AccountID__c}" id="organisation" required="true" >
                        <apex:actionSupport event="onchange" action="{!SelectServiceIns}" reRender="contact" status="status" oncomplete="getV(); return true;"  />
                    </apex:inputfield>
                </apex:pageBlockSectionItem>
                
                
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Date" for="datetime"/>
                    <apex:inputfield value="{!rep.Date__c}" id="theDate"/>
                </apex:pageBlockSectionItem>
                
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Address"/>
                    <apex:outputText value="{!BillingCity},{!BillingStreet}" id="address" >
                    </apex:outputText>

some code.....
This is controller for this page:
public class CtrlCallHospInsert {
  public Set<Id> selectedOrganisationsIds  { get; set; }
    public String selectedOrganisationsStr { get; set; }


public CallReportHosp__c rep {get; set;}

public Id AccIns{get;set;}
public String BillingCity{get;set;}
public String BillingStreet{get;set;}

private Account rep2;

public void applyFilterByOrganisations() {
        this.selectedOrganisationsIds = new Set<Id>();
        if(String.isBlank(this.selectedOrganisationsStr) || this.selectedOrganisationsStr == '[]') {
            return;
        }
        String[] OrganisationsIds = this.selectedOrganisationsStr.remove('[').remove(']').remove(' ').split(',');
        for(String s : OrganisationsIds) {
            if(!String.isBlank(s)) {
                rep.AccountID__c=s;
            }
        }
        this.selectedOrganisationsStr = null;
    }

private ApexPages.StandardController controller { get; set; }

    public CtrlCallHospInsert(ApexPages.StandardController controller) {
         this.controller = controller;
         this.rep = new CallReportHosp__c();
         this.rep.AccountID__c=NULL;
         this.rep.ContactID__c=NULL;
         this.rep.Duration__c='30 min';
         this.BillingCity=''; this.BillingStreet='';
         this.AccIns=NULL;
    }



public PageReference save(){
        
        try {
            insert rep;
        }catch (Exception e){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '"Something went wrong !"'));
        }
        PageReference pageRef = Page.CallsHospList;
        pageRef.setRedirect(true);
        return pageRef;
    }
    
    
public PageReference SelectServiceIns(){
System.debug('select ');
 System.debug('acc = '+this.AccIns);
 rep2=[Select id, BillingCity, BillingStreet  FROM Account where id=:this.AccIns];
 this.rep.AccountID__c=rep2.id;
 this.rep.put('AccountID__c',rep2.id);
 System.debug('new value= '+this.rep.get('AccountID__c'));
 System.debug('accvalue= '+AccIns);
      this.AccIns=rep2.id;
      System.debug('new acc = '+this.AccIns);
      this.BillingCity=rep2.BillingCity;
      this.BillingStreet=rep2.BillingStreet;  
return null;
}

    
 public PageReference cancel() {
        PageReference pageRef = Page.CallsHospList;
        pageRef.setRedirect(true);
        return pageRef;        
    }
    
}
And this is lookup page:
<apex:page standardcontroller="Account" recordsetvar="accounts" extensions="AccountsListforHosp" showheader="false" sidebar="false" title="Search" tabstyle="Account" id="pg">
        
    
     

       

    <apex:form >

       
            some code...
            
           
            
            <div id="resultsLoadingIndicator" class="waitingSearchDiv" style="position: relative; display: none; width: 100%; height: 420px; background: #fff;">
                <div class="waitingHolder" style="width: 75px; top: 59.8px;">
                    <img src="/img/loading.gif" class="waitingImage" title="{$Label.TM_Please_Wait}" />
                    <span class="waitingDescription">{!$Label.TM_Loading}</span>
                </div>
            </div>
            <div id="resultsPanel">
                <apex:outputpanel id="pnlSearchResults" style="background:white;height:420px;overflow-Y:auto;" layout="block">
                    
                                            
                    <script type="text/javascript">
                        function addSelectedOrganisations() {
                            var searchContext = "{!searchContext}";
                            var parentWindow = top.parent.window;
                            if(searchContext === "brick") {
                                parentWindow.opener.addSelectedBricks("{!selectedRecords}");
                            } else { if (searchContext === "pharma_chain") {
                                parentWindow.opener.addSelectedOrganisations("{!selectedRecords}");}
                                else {parentWindow.opener.addSelectedParents("{!selectedRecords}");}
                            } 
                            parentWindow.close();
                        }
                         function addSelectedOrganisationsIns() {
                            var searchContext = "{!searchContext}";                            
                            var parentWindow = top.parent.window;                            
                            if (searchContext === "pharma_chain") {
                                parentWindow.opener.addSelectedOrganisationsIns("{!selectedRecords}");}                               
                            parentWindow.close();
                        }
                    </script>

                    <apex:pageblocktable value="{!searchResults}" var="res">                   
                        <apex:column headervalue="" style="width:25px" rendered="{!ListCalls}">
                            <apex:facet name="header">
                                <input type="checkbox" id="checkAll" onclick="checkAllBoxes(this,'TM_search_checkbox');" />                                
                            </apex:facet>
                            <apex:inputcheckbox value="{!res.isSelected}" styleclass="TM_search_checkbox" />
                        </apex:column>
                        
                        <apex:column value="{!res.record.Name}" rendered="{!ListCalls}" />
                        <apex:column rendered="{!Not(ListCalls)}">
<!--                            <apex:outputLink value="javascript:top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!res.record.Id}','{!res.record.Name}', false)" rendered="{!NOT(ISNULL(res.record.Id))}">{!res.record.Name}</apex:outputLink> -->
<!--<apex:outputLink value="javascript:top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!res.record.Id}','{!res.record.Id}', false)" >{!res.record.Name}</apex:outputLink> -->
<apex:outputLink value="javascript:top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!res.record.Id}','{!res.record.Id}', false)" rendered="{!NOT(ISNULL(res.record.Id))}">{!res.record.Name}</apex:outputLink>

                        </apex:column>
                        <apex:column value="{!res.record.Proxima_External_Id__c}" />
                        <apex:column value="{!res.record.Brick_Description__c}" rendered="{!isBricksSearch}" />
                        <apex:column value="{!res.record.BillingCity}" rendered="{!isPharmacyChainsSearch}" />
                        <apex:column value="{!res.record.BillingStreet}" rendered="{!isPharmacyChainsSearch}" />

                    </apex:pageblocktable>

                </apex:outputpanel>
            </div>
            
some code

            </apex:panelgrid>
        </apex:pageblock>
    </apex:form>
</apex:page>


When i open main page ( inserting  new object ) and starting lookup page the value from lookup page passing to may main window. But if i starting lookup page again ( for example, i chosed false organization and would like to chose it again) my lookup page don't close and don't passing value to parent window and i have error" Uncaught TypeError: Cannot read property 'nextSibling' of null
    at ForeignKeyInputElement.applyValidationChanges (main.js:706)
    at Function.ForeignKeyInputElement.dispatchLookupChange (main.js:697)
    at doLookupPick (main.js:39)
    at lookupPick2 (main.js:45)
    at <anonymous>:1:19"
How can i solve this issue?