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
Harjeet Singh 13Harjeet Singh 13 

how to restrict a pop up to close if nothing is selected on page

Hi All,
Hope you all are doing good.

Dear all i stuck at a point and need help from all experts here.
Actually according to my requirement I have designed a page which will opens up when an user clicks a button on opportunity and this page consists 2 sections as "Account Commercial Address" and "Account Installation Address" section holding the coomercial address of the account and installation address of the account respectively.
I have also include a button "Add" button at the bottom of the page.Whenever an user is selecting the addresses on page and clicks on Add button the selected addresses the pop up window should close and page will get refreshed and selected address should come as a line item on opportunity.Till here I have developed and everything is working fine.
My issue is suppose an user is not selected any addresses and clicks on Add button then the user should get an error message on page itself something like" Please select atleast an address" but I am not able to achieve this particular thing after so much work. Right now even if an user clicks on Add button without selecting any address then also pop up is getting close and page is getting referesh.Ideally what i want to achieve is if nothing is selected then an error should be displayed and pop up should not be closed.
I am attaching my codes also.

Please help me out here.
Many thanks in advance.
<apex:page standardController="Opportunity" sidebar="false" showHeader="false"  extensions="TfB_SA_OpportunityCanvas_Controller">
<head>
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css" />
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
</head>
 <apex:form >

    <script type="text/javascript" src="/soap/ajax/31.0/connection.js"></script>
    <script type="text/javascript" src="/canvas/sdk/js/31.0/controller.js"></script>
<apex:pageBlock >
    <!-- Invoking the Canvas app, No parameters are passed from Opportunity -->
  <!--  <div align="center" id='spanDisplayLabel' style='border:px'>
    <apex:pageBlockSection title="New Installation Address" collapsible="false" columns="1" ></apex:pageBlockSection></div>-->
    <div align='Center' style='font-size:16px;'><br/><b><b>New Installation Address</b></b></div>
    <apex:canvasApp developerName="Tfb_SA_Canvas" width="100%" height="500px" />
    
    <script>
    
        Sfdc.canvas(function() { 
        
            /*
             * Description : This function subscribes to the Canvas application publish event
             *               'updateAddressEvent' and update Tina Address and Opportunity object              
             * Returns     : void
            */  
                  
            Sfdc.canvas.controller.subscribe({name : 'updateAddressEvent',
                onData : function (e) {
                    
                    try{
                    
                        /* Upsertion of Tina Address record starts */
                        sforce.connection.sessionId = '{!$Api.Session_ID}';
                        var ta= new sforce.SObject("TFB_SA_Tina_Address__c");
                        ta.Name = e.TinaLocationId;
                        if (e.Apartment && e.Apartment != 'null'){
                            ta.Tfb_SA_Apartment__c = e.Apartment;
                        }
                        if (e.Box && e.Box != 'null') {
                            ta.Tfb_SA_Box__c= e.Box;
                        }
                        if (e.Country && e.Country != 'null') {
                            ta.TfB_SA_Country__c = e.Country;
                        }
                        if (e.FloorNumber && e.FloorNumber != 'null') {
                            ta.Tfb_SA_Floor_Number__c = e.FloorNumber;
                        }
                        if (e.HouseNumber && e.HouseNumber != 'null') {
                            ta.Tfb_SA_House_Number__c = e.HouseNumber;
                        }
                        if (e.Municipality && e.Municipality != 'null') {
                            ta.Tfb_SA_Municipality__c = e.Municipality;
                        }
                        if (e.PostalCode && e.PostalCode != 'null') {
                            ta.Tfb_SA_Postal_Code__c = e.PostalCode;
                        }
                        if (e.Street && e.Street != 'null') {
                            ta.Tfb_SA_Street__c = e.Street;
                        }                       
                        if (e.SubHouseNumber && e.SubHouseNumber != 'null') {
                            ta.Tfb_SA_Sub_House_Number__c = e.SubHouseNumber;
                        }                        
                        if (e.SubLocation && e.SubLocation != 'null') {
                            ta.Tfb_SA_SubLocation__c = e.SubLocation;
                        }                        
                        if (e.TinaLocationId && e.TinaLocationId != 'null') {
                            ta.Tfb_SA_Tina_Location_Id__c = e.TinaLocationId;
                        }                        
                               
                        var result = sforce.connection.upsert("Tfb_SA_Tina_Location_Id__c", [ta]);
                        
                        /* Upsertion of Tina Address record ends */
                    
                        /* Insertion of Opportunity Installation Address starts */
                        
                        if (result[0].getBoolean("success")) {
                            var oppInstAdd = new sforce.SObject("Tfb_SA_Opportunity_Installation_Address__c");
                            oppInstAdd.TfB_SA_TinaOpportunity_Location_Id__c = e.TinaLocationId + '{!$CurrentPage.parameters.optyId}'; // Added for Upsert opertaion
                            oppInstAdd.Tfb_SA_Opportunity__c = '{!$CurrentPage.parameters.optyid}';
                            oppInstAdd.Tfb_SA_Tina_Address__c = result[0].id;
                            var oppresult = sforce.connection.upsert("TfB_SA_TinaOpportunity_Location_Id__c",[oppInstAdd]); // Modified from Insert to Upsert  
                            
                            
                            var accInstAdd = new sforce.SObject("TfB_SA_Account_Installation_Address__c");
                            accInstAdd.Tina_Account_LocationId__c= e.TinaLocationId + '{!$CurrentPage.parameters.accId}'; // Added for Upsert opertaion
                            accInstAdd.TfB_SA_Account__c= '{!$CurrentPage.parameters.accid}';
                            accInstAdd.TfB_SA_Tina_Address__c= result[0].id;
                            var accresult = sforce.connection.upsert("Tina_Account_LocationId__c",[accInstAdd]); // Modified from Insert to Upsert                               
                            
                            if (oppresult[0].getBoolean("success")) {
                                // closing the popup page
                                window.close()
                                } else {
                                alert("Error : Could not update this Opportunity" + oppresult[0].errors.message);
                            }
                        } else {
                            alert("Error : Could not Insert/Update the Tina Address" + result[0].errors.message);
                        }
                        
                        /* Insertion of Opportunity Installation Address record ends */
                    
                    } catch (ex){
                        alert ("Exception :" + ex);
                    }
                }
           });
        });     
        
     </script>
     
     <!--Below sections added as part of Rel16.1-->
     <!--Below script implements the checkbox selection for account-->
<script>
function doCheckboxChange(cb,itemId){ 
  
    if(cb.selected){
        
        SelectItem(itemId);        
    }
    else{
        
        aDeselectItem(itemId);
    }
}
</script>     
  <!--   <div align="center" id='spanDisplayLabel' style='border:px'>
    <apex:pageBlockSection title="Existing Account Address" collapsible="false" columns="1"></apex:pageBlockSection></div>-->
    <div align='Center' style='font-size:16px;'><br/><b><b>Existing Account Address</b></b></div>
    <p><b>Select and add one or more Existing address(es) of Account shown below as Installation address(es) on this Opportunity</b></p><br/>
   
   <apex:pageBlock >  
     <!------------------Existing Installation Address------------------->
      <!--Commercial address section start--->
              <div align="left">
           <apex:pageBlockSection title="Account Commercial Address" collapsible="false" columns="1" >
        
            <apex:pageBlockTable value="{!commAddress}" align="left" var="c" id="table" rendered="{!comChkFlag}">                            
                 <apex:column style="Width:10px"> 
                           <apex:inputCheckbox value="{!commFlag}" id="inputId">
                        </apex:inputCheckbox>                                                            
                 </apex:column>  
                 <apex:column style="Width:800px">
                     <apex:outputText value="{!c.TfB_SA_Commercial_Address__c}"></apex:outputText>
                 </apex:column>  
            </apex:pageBlockTable>
          </apex:pageBlockSection></div> <apex:outputText style="color:red" value="{!messageCmm}" rendered="{!comaddFlag}"></apex:outputText>
                         <!--Commercial address section Ends--->     
                      
                     
                     
                                  <!--Account installation address start--->
                                  
             <div align="left">
             <apex:pageBlockSection title="Account Installation Address(es)" collapsible="false" columns="1">           
               <apex:pageBlockTable value="{!CurrentList}"  align="left" var="c" id="table1" rendered="{!acChkFlag}">
                 <apex:column style="Width:10px"> 
                    <apex:inputCheckbox value="{!c.selected}" id="inputId" onchange="doCheckboxChange(this,'{!c.vSub.Id}')">
                         </apex:inputCheckbox>                                                                     
                 </apex:column>                 
                 <apex:column style="Width:800px">
                     <apex:outputText value="{!c.vSub.TfB_SA_Concatenated_Tina_Address__c}"></apex:outputText>
                 </apex:column>                 
               </apex:pageBlockTable>
             </apex:pageBlockSection>   </div><apex:outputText style="color:red" value="{!messageAcc}" rendered="{!msgFlag}"></apex:outputText>  
                               <!--Account installation address End--->  
                                         <!----------------------Account Ends------------------>
            </apex:pageBlock>                             
      <div align="center"><apex:commandButton action="{!Add}" value="Add"  id="button" oncomplete="javascript:CloseAndRefresh()"/></div> 
      
      <script language="JavaScript" type="text/javascript">
            function CloseAndRefresh(){
        <!--window.opener.location.href="/{!$CurrentPage.parameters.id}";-->
          window.top.close();    
      }
        </script>
         
     </apex:pageBlock>
   </apex:form>
  </apex:page>
 
Public Class TfB_SA_OpportunityCanvas_Controller{
    
    public string accId;
    public string oppId;
    public string tinaLocId;      
    public List<wrapSubscription> SubscriptionSetList{get;set;}  
    public TfB_SA_Account_Installation_Address__c vSub{get;set;}  
    public set<TfB_SA_Account_Installation_Address__c> selectedSubscription{get;set;}
    public list<TfB_SA_Opportunity_Installation_Address__c> opplist{get;set;}
    public list<Account> commAddlist {get;set;}
    public boolean commFlag{get;set;} 
    public boolean comChkFlag{get;set;}
    public boolean acChkFlag{get;set;}
    public boolean msgFlag{get;set;}
    public Boolean comaddFlag{get;set;}
    public String messageAcc{get;set;}
    public String messageCmm{get;set;} 
    


    //constructor
    public TfB_SA_OpportunityCanvas_Controller(ApexPages.StandardController controller) {    
    oppId=ApexPages.currentPage().getParameters().get('optyId');
    //accId=ApexPages.currentPage().getParameters().get('accid');
    tinaLocId=ApexPages.currentPage().getParameters().get('tinaLocationId');
    system.debug('Account ID:'+accId);
   // accId=[SELECT AccountId From Opportunity Where ID =:oppId];
     vSub= new TfB_SA_Account_Installation_Address__c();  
     this.selectedSubscription = new set<TfB_SA_Account_Installation_Address__c>();      
     SubscriptionSetList = new List<wrapSubscription>();
     commAddlist= new list<Account>();
     messageCmm='No commercial addresses found on Account.';   
     commFlag=false;     
     comChkFlag=true;
     acChkFlag=true;
     msgFlag=false;
     comaddFlag=false;   
     List<Account> templist1=new List<Account>();
     tempList1=getcommAddress();
     List<wrapSubscription> templist=new list<wrapSubscription>();
     templist=getCurrentList();   
      
    
    } 
       
     //Below method is used to fetch Commercial Address from Account     
    public list<Account> getcommAddress(){
    commAddlist=[SELECT TfB_SA_Tina_Address__c,TfB_SA_Commercial_Address__c FROM Account Where id IN (SELECT Accountid From Opportunity Where ID=:oppId)];
    system.debug('enter2 com');    
    if(commAddlist.size()==0 || (commAddlist.size()==1 && commAddlist[0].TfB_SA_Commercial_Address__c == null)){    
    comaddFlag=true;
    comChkFlag=false;   
    }  
    
    return commAddlist;
    
    }
            
            
            
    //Following function implements wrapper logic 
    public List<wrapSubscription> getCurrentList( ){        
        updateSelectedSubscriptions();  
        SubscriptionSetList = new List<wrapSubscription>();
        for (TfB_SA_Account_Installation_Address__c vSubscription : (List<TfB_SA_Account_Installation_Address__c>)SubSetController.getRecords( )){
                SubscriptionSetList.add(new wrapSubscription(vSubscription));
                    
    }
     if(SubscriptionSetList.Size()>0){
        msgFlag=false;
        acChkFlag=true;         
        system.debug('acChkFlageee'+acChkFlag);
        return SubscriptionSetList;
        }
        else{
        acChkFlag=false;
        msgFlag=true;         
        messageAcc='No installation addresses found on Account.';        
        ///ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'No installation addresses found on account. You can add an installation address by clicking on the Add Installation Address button on the account'));
        system.debug('enter1'+SubscriptionSetList.Size());
        system.debug('acChkFlag'+acChkFlag);
        return null;
        }
        
   }
      public ApexPages.StandardSetController SubSetController{ 
        
        get{            
            if(SubSetController == null){                                
                SubSetController = new ApexPages.StandardSetController([SELECT Id,TfB_SA_Tina_Address__c,Location_ID__c,Tina_Account_LocationId__c,TfB_SA_Concatenated_Tina_Address__c,TfB_SA_Account__c FROM TfB_SA_Account_Installation_Address__c WHERE TfB_SA_Account__c IN (SELECT Accountid From Opportunity Where ID=:oppId)]);
                }
            return SubSetController;
          }set;
     }
    
   //This method update the selected Subscriptions List in the wrapper Class
    public void updateSelectedSubscriptions(){
        for(wrapSubscription cs: SubscriptionSetList){
            if(cs.selected){              
                selectedSubscription.add(cs.vSub);               
              }
            else{            
                if(selectedSubscription.contains(cs.vSub))
                selectedSubscription.remove(cs.vSub);                              
            }
           // wrapObj.put(cs,cs.vSub);
        }
        system.debug('selectedSubscription'+selectedSubscription);
    }
       
    //Wrapper class logic      
    public class wrapSubscription{
        public TfB_SA_Account_Installation_Address__c vSub {get; set;}        
        public Boolean selected {get; set;}       
        public wrapSubscription(TfB_SA_Account_Installation_Address__c a){
            vSub = a;
            selected = false;
        }
        public wrapSubscription(TfB_SA_Account_Installation_Address__c c,string s){
            vSub=c;
            selected=true;
        }       
        
    }
    
    //Below Method is used to Upsert Commercial Address from  Account to Opportunity Installation Address
    public PageReference AddComm() {
    List<TfB_SA_Opportunity_Installation_Address__c> templist = new List<TfB_SA_Opportunity_Installation_Address__c>();    
    templist=[Select Location_ID__c,TfB_SA_Tina_Address__c,TfB_SA_TinaOpportunity_Location_Id__c FROM TfB_SA_Opportunity_Installation_Address__c Where TfB_SA_Opportunity__c=:oppId AND Location_ID__c=:tinaLocId];
     system.debug('templist::'+templist);
   //  system.debug('templist'+templist);
     
     if(templist.size()==0){
         TfB_SA_Opportunity_Installation_Address__c objtemp1 = new TfB_SA_Opportunity_Installation_Address__c();         
        // objtemp1.Location_ID__c=tinaLocId;
     objtemp1.TfB_SA_TinaOpportunity_Location_Id__c=tinaLocId+oppId;     
     objtemp1.TfB_SA_Tina_Address__c=commAddlist[0].TfB_SA_Tina_Address__c;
     objtemp1.TfB_SA_Opportunity__c=oppId;
     insert(objtemp1);
         }
         
      else{
         TfB_SA_Opportunity_Installation_Address__c objtemp =[Select Location_ID__c,TfB_SA_Tina_Address__c,TfB_SA_TinaOpportunity_Location_Id__c FROM TfB_SA_Opportunity_Installation_Address__c Where TfB_SA_Opportunity__c=:oppId AND Location_ID__c=:tinaLocId]; 
        // objtemp.Location_ID__c=tinaLocId;
     objtemp.TfB_SA_TinaOpportunity_Location_Id__c=tinaLocId+oppId;     
     objtemp.TfB_SA_Tina_Address__c=commAddlist[0].TfB_SA_Tina_Address__c;
     //objtemp.TfB_SA_Opportunity__c=oppId;
     update(objtemp);
     }
     return null;  
     }    
    
    
    //Below Method is used to Upsert Commercial Address from  Account Installation Address to Opportunity Installation Address
     public PageReference Add() {
     
     updateSelectedSubscriptions();
     if(commFlag){
            AddComm();
            commFlag=false;
            }
               
     system.debug('selectedSubscription'+selectedSubscription);
     
   
     List<TfB_SA_Opportunity_Installation_Address__c> listele = new List <TfB_SA_Opportunity_Installation_Address__c>();       
     List<TfB_SA_Opportunity_Installation_Address__c> objlist = new List <TfB_SA_Opportunity_Installation_Address__c>();
     listele=[SELECT TfB_SA_Tina_Address__c,TfB_SA_TinaOpportunity_Location_Id__c From TfB_SA_Opportunity_Installation_Address__c];
     
     //TfB_SA_Opportunity_Installation_Address__c 
     
     for(TfB_SA_Account_Installation_Address__c list2 :selectedSubscription){

         listele=[SELECT Location_ID__c,TfB_SA_Tina_Address__c,TfB_SA_TinaOpportunity_Location_Id__c From TfB_SA_Opportunity_Installation_Address__c  WHERE TfB_SA_Opportunity__c=:oppId AND Location_ID__c=:list2.Location_ID__c];
         //if(listele.TfB_SA_TinaOpportunity_Location_Id__c!=list2.TfB_SA_Opportunity_Installation_Address__c){   
         system.debug('sizeeeee:'+listele);
         if(listele.size()==0){
             TfB_SA_Opportunity_Installation_Address__c obj = new TfB_SA_Opportunity_Installation_Address__c();
             obj.TfB_SA_TinaOpportunity_Location_Id__c=list2.Location_ID__c+oppId;
             obj.TfB_SA_Tina_Address__c=list2.TfB_SA_Tina_Address__c;
             obj.TfB_SA_Opportunity__c=oppId;
             insert(obj);
         }
         else{
         List<TfB_SA_Opportunity_Installation_Address__c> obj1 = new List<TfB_SA_Opportunity_Installation_Address__c>();
         obj1 =[SELECT Location_ID__c,TfB_SA_Opportunity__c,TfB_SA_Tina_Address__c,TfB_SA_TinaOpportunity_Location_Id__c From TfB_SA_Opportunity_Installation_Address__c WHERE TfB_SA_Opportunity__c=:oppId AND Location_ID__c=:list2.Location_ID__c];  
            for(TfB_SA_Opportunity_Installation_Address__c oplist : obj1 ){
             oplist.TfB_SA_TinaOpportunity_Location_Id__c=list2.Location_ID__c+oppId;
             oplist.TfB_SA_Tina_Address__c=list2.TfB_SA_Tina_Address__c;
             //obj1.TfB_SA_Opportunity__c=oppId;
             update(oplist);
             }
        } 
       
     
     
     }
     
     return null;  }    
                 
         
}

 
Best Answer chosen by Harjeet Singh 13
Sunil MadanaSunil Madana
Hi Harjeet,
I created two visualforce pages in order to achieve your result and below is the code.

Code / VF page-1:
In the below page, i open a new window using Javscript code.
<apex:page >
    <script>       
        function openwindow() {
            var my_window = window.open("/apex/VF_Testing5","_blank", "toolbar=yes, scrollbars=yes, resizable=yes, top=500, left=500, width=400, height=400");
            my_window.focus();
            my_window.onblur = function() {
                my_window.close();
            };
        }
    </script>
    <input type="button" onclick="openwindow();" value="Click me!" />
</apex:page>
Code / VF page-2:
In the below page, as the window is already opened i do some validation and throw error before this po-up window is closed.
<apex:page id="a" showHeader="false">
    <script>
        var hook = false;
        function fm(){
            var name = document.getElementById("a:b:c:input").value;
            document.getElementById("a:b:c:output").innerHTML = "The typed value is "+name;
            if( name != null || name.length > 0) {
                hook = true;
            }
        }
        window.onbeforeunload = function() { if(hook == false) { return "You have not filled in all the text"; } else { window.close; }  }
    </script>
    <apex:form id="b">
        <apex:pageBlock id="c">
            <apex:inputText id="input" onchange="fm();" /><br/><br/>
            <apex:outputText id="output"></apex:outputText>
        </apex:pageBlock>
    </apex:form>
</apex:page>
You may copy the page-2 code in your pop-up window script to restrict pop-up close unless the field is filled-in with some text.

Appreciate your feedback on this answer, if it helps.

Thanks, Sunil.

All Answers

Sunil MadanaSunil Madana
Hi Harjeet,
I created two visualforce pages in order to achieve your result and below is the code.

Code / VF page-1:
In the below page, i open a new window using Javscript code.
<apex:page >
    <script>       
        function openwindow() {
            var my_window = window.open("/apex/VF_Testing5","_blank", "toolbar=yes, scrollbars=yes, resizable=yes, top=500, left=500, width=400, height=400");
            my_window.focus();
            my_window.onblur = function() {
                my_window.close();
            };
        }
    </script>
    <input type="button" onclick="openwindow();" value="Click me!" />
</apex:page>
Code / VF page-2:
In the below page, as the window is already opened i do some validation and throw error before this po-up window is closed.
<apex:page id="a" showHeader="false">
    <script>
        var hook = false;
        function fm(){
            var name = document.getElementById("a:b:c:input").value;
            document.getElementById("a:b:c:output").innerHTML = "The typed value is "+name;
            if( name != null || name.length > 0) {
                hook = true;
            }
        }
        window.onbeforeunload = function() { if(hook == false) { return "You have not filled in all the text"; } else { window.close; }  }
    </script>
    <apex:form id="b">
        <apex:pageBlock id="c">
            <apex:inputText id="input" onchange="fm();" /><br/><br/>
            <apex:outputText id="output"></apex:outputText>
        </apex:pageBlock>
    </apex:form>
</apex:page>
You may copy the page-2 code in your pop-up window script to restrict pop-up close unless the field is filled-in with some text.

Appreciate your feedback on this answer, if it helps.

Thanks, Sunil.
This was selected as the best answer
Harjeet Singh 13Harjeet Singh 13
Thanks sunil for your reply.
Actually I have got the solution from some resources shared on Internet.

Although after implementing my solution I have also tried with the one as suggested by you in one of my dev org.Actually the solution suggested by you will be best fir for the text box cases but in my scenario I was playing with checkbox.I have little twiked our code here and there according to my rquirement and it also worked.Now I have 2 solutions for the same requirements.
Thanks
Sunil MadanaSunil Madana
Thanks for the response Harjeet.