+ Start a Discussion
Arup..Arup.. 

Pop up window in visualforce

Hi,

 I am new in Salesforce...I want to design a pop up window. The window will appear after save button is hit which will show the values those an user has entered as input. After the pop up comes out then the user will click the ok in pop up and the page will be redirected to the object view page.

 

Now how can I implement it throgh java script or any other possible way.

Can u pls provide some sample coding for it.

 

Thanks in advance,

Best Answer chosen by Admin (Salesforce Developers) 
Chamil MadusankaChamil Madusanka

Hi,

 

I will provide an example for popup. Try to understand and convert it to your requirement.

 

<apex:page standardController="Contact" extensions="TestPopup">

<apex:form >
<apex:pageBlock >
<apex:commandButton value="show popup" action="{!showPopup}" rerender="popup" status="status"/>


  
             <apex:outputPanel id="popup">

                <apex:outputPanel id="popInnerOutputPnl" styleClass="customPopup" layout="block" rendered="{!displayPopUp}">
                     <apex:commandButton value="X" title="Close the popup" action="{!closePopup}" styleClass="closeButton" rerender="popup">
                     </apex:commandButton>
                     <apex:pageblockSection >                         
                         
                         <apex:pageblockSectionItem >
                          <apex:outputLabel value="Email" for="address"></apex:outputLabel>
                             <apex:inputField id="address" value="{!Contact.Email}"/>
                         </apex:pageblockSectionItem>
                     </apex:pageblockSection>
                     <apex:commandButton value="Ok" action="{!redirectPopup}" styleClass="closeButton" rerender="popup">
                     </apex:commandButton>
                </apex:outputPanel>
            </apex:outputPanel>
            
            </apex:pageBlock>
            
              </apex:form>
              
                  <style type="text/css">
.customPopup {
    background-color: white;
    border-style: solid;
    border-width: 2px;
    left: 20%;
    padding: 10px;
    position: absolute;
    z-index: 9999;
    /* These are the 3 css properties you will need to tweak so the pop 
                            up displays in the center of the screen. First set the width. Then set 
                            margin-left to negative half of what the width is. You can also add 
                            the height property for a fixed size pop up.*/
    width: 500px;
    top: 20%;
}

.disabledTextBox {
    background-color: white;
    border: 1px solid;
    color: black;
    cursor: default;
    width: 90px;
    display: table;
    padding: 2px 1px;
    text-align:right;
}   

.closeButton {
    float: right;
}
</style>


</apex:page>

 

public with sharing class TestPopup {

    public Boolean displayPopup {get;set;}

    public TestPopup(ApexPages.StandardController controller) {

    }
    
    public void showPopup()
    {
        
    displayPopup = true;

    
    }
    
    public void closePopup() {
        displayPopup = false;
        
    }
    
    public PageReference redirectPopup()
    {
    displayPopup = false;
        //Please uncomment below 3 statements and replace YourObjectId
       // PageReference p=new Pagereference('/'+YourObjectId);
       //  p.setRedirect(true);
       //  return p;
        
    }
    


}

 If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.

 

chamil's blog

All Answers

Chamil MadusankaChamil Madusanka

Hi,

 

I will provide an example for popup. Try to understand and convert it to your requirement.

 

<apex:page standardController="Contact" extensions="TestPopup">

<apex:form >
<apex:pageBlock >
<apex:commandButton value="show popup" action="{!showPopup}" rerender="popup" status="status"/>


  
             <apex:outputPanel id="popup">

                <apex:outputPanel id="popInnerOutputPnl" styleClass="customPopup" layout="block" rendered="{!displayPopUp}">
                     <apex:commandButton value="X" title="Close the popup" action="{!closePopup}" styleClass="closeButton" rerender="popup">
                     </apex:commandButton>
                     <apex:pageblockSection >                         
                         
                         <apex:pageblockSectionItem >
                          <apex:outputLabel value="Email" for="address"></apex:outputLabel>
                             <apex:inputField id="address" value="{!Contact.Email}"/>
                         </apex:pageblockSectionItem>
                     </apex:pageblockSection>
                     <apex:commandButton value="Ok" action="{!redirectPopup}" styleClass="closeButton" rerender="popup">
                     </apex:commandButton>
                </apex:outputPanel>
            </apex:outputPanel>
            
            </apex:pageBlock>
            
              </apex:form>
              
                  <style type="text/css">
.customPopup {
    background-color: white;
    border-style: solid;
    border-width: 2px;
    left: 20%;
    padding: 10px;
    position: absolute;
    z-index: 9999;
    /* These are the 3 css properties you will need to tweak so the pop 
                            up displays in the center of the screen. First set the width. Then set 
                            margin-left to negative half of what the width is. You can also add 
                            the height property for a fixed size pop up.*/
    width: 500px;
    top: 20%;
}

.disabledTextBox {
    background-color: white;
    border: 1px solid;
    color: black;
    cursor: default;
    width: 90px;
    display: table;
    padding: 2px 1px;
    text-align:right;
}   

.closeButton {
    float: right;
}
</style>


</apex:page>

 

public with sharing class TestPopup {

    public Boolean displayPopup {get;set;}

    public TestPopup(ApexPages.StandardController controller) {

    }
    
    public void showPopup()
    {
        
    displayPopup = true;

    
    }
    
    public void closePopup() {
        displayPopup = false;
        
    }
    
    public PageReference redirectPopup()
    {
    displayPopup = false;
        //Please uncomment below 3 statements and replace YourObjectId
       // PageReference p=new Pagereference('/'+YourObjectId);
       //  p.setRedirect(true);
       //  return p;
        
    }
    


}

 If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.

 

chamil's blog

This was selected as the best answer
PpapasPpapas

chamil this is great. you are a savior :)

 

is it possible to create a test method unit for your class. 

 

we would really appreciate for us newbiees in here

 

thanks

Chamil MadusankaChamil Madusanka

Hi,

 

Yes, It is possible to create test methods to this class(in normal manner).

 

If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.

 

Chamil's Blog

PpapasPpapas

Great, chamil thanks,

 

can you you help us out with this class? thanks in advance

 

Chamil MadusankaChamil Madusanka

Hi,

 

You mean, you need a test class for the class which I have posted before. There is no any implementation to test. Therefore, you have to implment your scenario and after that consider about the test class. I just gave the example to get an idea about the popup. I'll help you to write the test class.

 

If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.

 

chamil's blog

PpapasPpapas

Awesome, thanks chamil

Srinath TeramSrinath Teram

Chamil,

 

Will this inactivate the other section of VF page other than the pop up. I mean a grayout? Could you please help me with gray out? I'm kinda green to Jquery/javascript/css !

 

Thanks.

Chamil MadusankaChamil Madusanka

@Srinath

 

This example has not a disabled backgroup.

 

Refer this link. It has disabled background : http://www.salesforcegeneral.com/salesforce-modal-dialog-box/

 

If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.

Creating Splash ScreensCreating Splash Screens

Hi 

 

I am new to salesforce and need a sample code for a popup window when a user login for the first time only.Your help will be appriciated.

ppapas_98ppapas_98

Hey Splash,

 

i hope this get you started

 

<script>
if(!{!Account.IsSubmittedForApproval__c})
alert('Please Submit the Account for Approval.');
</script>

 

this is a script for alerts in Account approvals. make sure you put it inside the <apex:page> </apex:page>

 

i hope it helps

unidhaunidha
Hi Chamil,

I wonder if we want to refresh other panel after we closing the popup window, why we can't use reRender?I tried and it does not work.I am not understand because reRender suppose to render the panel that we want to.Example:

<apex:commandButton value="Ok" action="{!redirectPopup}" styleClass="closeButton" rerender="nameofPaneltheoutsidepopup">
shoba shobashoba shoba

Hi Arup

i have same requirement like your. Can you please share your code.



Thanks
Shobana

Mohan Raj 33Mohan Raj 33
@Arup Hi, 
I have problem on the pop up window My code is as like your code Can you help me to solve my code issue?
Thanks
Mohan
mahendra chowdarymahendra chowdary
Hi Chamil

I am using your example but in this i got one error

Like :  
Error: Compile Error: unexpected token: 'redirectPopup' at line 22 column 28
sai dhanasai dhana
Hi Chamil Madusanka...

i have used your example for popup window its working fine in my inline visualforce page. but  when we close the popup window what ever the changes we have done before clicking the "X"  those should be rollbacked when we close the popup(suppose i have checked the check box and entered the data in inputtext field and the click on the save button then popup will come again i entered some data then i dont what the save then  i clicked the "X" button to close popup then the check box should be unchcked and input text fileds should be blank). can you please help me how to achive it.  please send me sample code to be used in inline visualforce page. i have tried to refresh page when command button "X" is clicked using rerender. page is refreshing but changes are not getting rollback. 

Thanks,
sai
Mohan Raj 33Mohan Raj 33
@sai dhana I also doing the update fields using the pop up window may be it will help you, 
My controller,
public class AccountEditController {

    public String closePopup { get; set; }

    accountwrapper1 makeEdit;
    List<accountwrapper1> listAccount = new List<accountwrapper1>();
    List<Account> selectableAccount = new List<Account>();
    //set<Account> selectableAccount2 = new set<Account>();
    //public Boolean showPanel {get; set;}
    public Boolean showPopup { get; set; }
   
   public AccountEditController() {
          showPopup = False;
         //showPanel = False;
   }
    
    public List<accountwrapper1> getAccounts() {
        if(listAccount == Null){
            for(Account a: [SELECT Id, Name, BillingCountry, Phone FROM Account])
            listAccount.add(new accountwrapper1(a));
            return listAccount; }
        else{
            listAccount.clear();
            for(Account a: [SELECT Id, Name, BillingCountry, Phone FROM Account])
            listAccount.add(new accountwrapper1(a));
            return listAccount;            
            }           
    }
    
     public PageReference showToPopup() {
   // public PageReference showToPanel() {
        showPopUp = True;
        return Null;
        //showPanel  = True;
        }
        
     public PageReference getSelectable() {
         system.debug('Hello');
        selectableAccount.clear();
        for(accountwrapper1 accwrapper : listAccount)
        if(accwrapper.selected == True)
        selectableAccount.add(accwrapper.acc);
        system.debug(selectableAccount);
        return Null;              
    }
    
    public string BillingCountry {
        get; 
        set;
    }
    
    
    /*public PageReference Savemeth() {
        for(account acc :selectableAccount ) {
                acc.BillingCountry = BillingCountry;
                selectableAccount2.add(acc);
                 
        }    
    update selectableAccount2;
    showPopup = False;
    return Null;
    
    }*/
    
    public PageReference Savemeth() 
    {
        map<Id, Account> mapAccountForUpdate = new map<Id, Account>();
        for(account acc :selectableAccount ) 
        {
            system.debug('BillingCountry: '+BillingCountry);
            acc.BillingCountry = BillingCountry;
            mapAccountForUpdate.put(acc.Id, acc);
        }    
        update mapAccountForUpdate.values();
        selectableAccount = new List<Account>();
        showPopup = Null;
        BillingCountry = '';
        //showPopup = False;
        return null;
    }
    
    public PageReference cancelmeth() {        
        return Null;
    }
    
    public PageReference closePopup() {
        showPopup = Null;
        BillingCountry = '';
        //showPopup = False;   
        return Null;
    }

    public PageReference GetSelectedAccounts()
    {
       if(selectableAccount.size()>0) {
        system.debug(selectableAccount.size());
        system.debug(selectableAccount);
        showPopup = Null;
        return Null;
        }
        else
        showPopup = Null;
        return Null;
    } 
    
    
     public class accountwrapper1
    {             
        public Account acc{get; set;}      
        public Boolean selected {get; set;}
        public accountwrapper1(Account a)
        {
            acc = a;
            selected = False;
        }
    }
}

and my page:
<apex:page controller="AccountEditController" applyHtmlTag="true">
<head>
    <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />
</head>

<script>
    $(document).ready(function(){    
        console.log('page loaded');
        select();        
    });
    
    function showPopUp(){
        showToPopup();
    }
    
    function select(){
        var checkboxes = $("input[type='checkbox']");
        console.log(checkboxes);
        $("[id*='sbbutton']").attr("disabled", !checkboxes.is(":checked"));
        
    
        $('[id*=chkb1]').change(function(){
            
           
            $("[id*='chkb2']").attr("checked",this.checked);
            getSelectable();
            var checkboxes = $("input[type='checkbox']");
            
            $("[id*='sbbutton']").attr("disabled", !checkboxes.is(":checked"));
            
        });  
        
        $('[id*=chkb2]').click(function(){

                        
            if($('[id*=chkb2]').length== $("[id*='chkb2']: checked").length)
             {          
                 $("[id*='chkb1']").attr("checked",this.checked); 
                 getSelectable();      
                                     
             }
             else
             {    
                 var checkboxes = document.getElementsByTagName('input');
                 console.log(checkboxes);
                 var counter = 0;
                 var counter1 = 1;

                 for (var i = 0; i < checkboxes.length; i++) {
                     if (checkboxes[i].type == 'checkbox') {
                         counter++;
                         console.log(counter);
                         if(checkboxes[i].checked == true){
                             counter1++;
                             console.log(counter1);
                         }
                     }
                 }           
                 if(counter==counter1){
                     $("[id*='chkb1']").attr("checked",this.checked);   
                     getSelectable();
                 } else {
                      $("[id*='chkb1']").removeAttr("checked");   
                      getSelectable(); 
                  }                  
             }   
             
             var checkboxes = $("input[type='checkbox']");
            $("[id*='sbbutton']").attr("disabled", !checkboxes.is(":checked"));        
        }); 
    } 

</script>
    <style type="text/css">
    .PopupBackground{
        background-color: white;
        opacity: 0.8;
        filter: alpha(opacity = 20);
        position: absolute;
        width: 100%;
        height: 200%;
        top: -100px;
        left: 10px;
        z-index: 9998;
    }
    .AccountEdit{
        background-color: white;
        border-width: 8px;
        border-style: solid;
        z-index: 9999;
        left: 30%;
        padding:10px;
        position: absolute;
        width: 350px;
        margin-left: 75px;
        top:300px;
    }
    </style>
        <apex:form >
            <apex:actionFunction name="getSelectable" action="{!getSelectable}" reRender="Output"/>
            <apex:actionFunction name="showToPopup" action="{!showToPopup}" reRender="Output"/>
            <apex:pageBlock Title="List of Accounts" >
               
                   <apex:pageBlockButtons location="top">
                        <!-- <apex:commandButton value="Get selected Records" action="{!showToPopup}" rerender="Output" id="button"/> -->
                        <input type="submit" value="Get selected Records" onclick="showPopUp();return false;" id="sbbutton" style="height:20px;margin: 1px;padding: 2px 3px;border: 1px solid #b5b5b5;border-bottom-color: #7f7f7f;
                                         background: #e8e8e9 url(/img/alohaSkin/btn_sprite.png) repeat-x right top;font-weight: bold;font-size: .9em;-moz-border-radius: 3px;-webkit-border-radius: 3px;border-radius: 3px"/>
                       
                        <apex:commandButton value="cancelPopup" action="{!closePopup}" rendered="output"/>
                      <!-- <apex:commandButton value="Get selected Records" action="{!showToPanel}" rerender="Output" id="button"/>---->
                   
                   </apex:pageBlockButtons>
                   
                 <!-- {!showPanel}---->
                      <apex:outputPanel id="Output">
                          <apex:outputPanel styleClass="PopupBackground" layout="black" rendered="{!showPopup}">
                              <apex:outputPanel styleClass="AccountEdit" layout="black" rendered="{!showPopup}">
                         <!---  <apex:outputPanel rendered="{!showPanel}">----->
                           <!---{!showPanel}---------->
                               <apex:outputLabel value="BillingCountry: "></apex:outputLabel>
                               <apex:inputText id="BillingCountry" value="{!BillingCountry}" size="40" style="height:13px;font-size:11px;"/><br />                   
                               <center><apex:commandButton value="save" action="{!Savemeth}" reRender="Initialtable,Output" oncomplete="select();"/>
                              <!-- <apex:commandButton value="cancel" action="{!cancelmeth}"/>---->
                               <apex:commandButton value="cancelPopup" action="{!closePopup}"/></center>
                                </apex:outputPanel>
                            </apex:outputPanel>                   
                        </apex:outputPanel>  
                 <!--   <apex:commandButton value="cancelPopup" action="{!closePopup}"/>--->
                   <apex:pageBlockSection Title="List of Available Accounts" columns="1" collapsible="true">
                            <apex:pageblockTable value="{!accounts}" var="a" id="Initialtable">
                            
                                <apex:column >
                                    <apex:facet name="header">
                                        <apex:inputCheckbox value="{!a.selected}" id="chkb1">
                                            <!-- <apex:actionSupport event="onclick" action="{!getSelectable}" reRender="Output"/>    -->
                                        </apex:inputCheckbox>
                                    </apex:facet>
                                    <apex:inputCheckbox value="{!a.selected}" id="chkb2" />
                                   <!-- <apex:actionSupport event="onclick" action="{!getSelectable}" reRender="Output"/> -->
                                </apex:column>
                                
                                <apex:column headervalue="Account Name" value="{!a.acc.Name}" width="200"/>
                                <apex:column headervalue="Phone" value="{!a.acc.Phone}" width="300"/>
                                <apex:column headervalue="Billing Country" value="{!a.acc.BillingCountry}" width="300"/>
                                                  
                            </apex:pageblocktable>
                   </apex:pageBlockSection>
                    
            </apex:pageblock>
        </apex:form>
</apex:page>

if it help note the best answer it's will help to other please.
Sagar Nagvekar 14Sagar Nagvekar 14
Code for creating popup window in Visualforce :- 2 Visualforce pages are required for this. Each VF page has its own controller.
// The controller for main VF page vfAssignNewAccountToContact
public with sharing class AssignNewAccountToContact
{
    public Contact c {get;set;}
    public String selectedAccountName   {get;set;}
    public String selectedAccountId {get;set;}
 
    public AssignNewAccountToContact()
    {
        selectedAccountName = '';
        selectedAccountId = '';
        c = [select id, name from Contact where id = :ApexPages.currentPage().getParameters().get('id')];
        System.debug('////////////c is ' + c);
    }
   
    public pageReference changeTheAccount()
    {
        System.debug('//////////selectedAccountId is ' + selectedAccountId);
        System.debug('//////////selectedAccountName is ' + selectedAccountName);
      
        if(selectedAccountId != '')
        {
            System.debug('//////////selectedAccountId is not null, so proceeding ');
            c.accountId = selectedAccountId;
            update c;
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.info, 'New account assigned successfully'));
           
            /*
              Make variables null, so that if something is typed now in the textbox,
              it gives error message if "Assign new account" is clicked again.
            */
            selectedAccountId = '';
            selectedAccountName = '';
        }
        else
        {
            System.debug('//////////selectedAccountId is null');
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.error, 'Kindly select an account by clicking on Lookup'));
        }       
        return null;
    }
   
    //For clearing success/error message shown on the VF page after Lookup is clicked.
    public pageReference clearMessages()
    {
        ApexPages.getMessages().clear();
        return null;
    }
}
<!--
  VF page name :- vfAssignNewAccountToContact
  Main VF page for assigning new account to a contact. Go to an existing contact record and add
  /apex/vfAssignNewAccountToContact?id=<ContactRecordID> to the URL to view this VF page.
-->
<apex:page controller="AssignNewAccountToContact">
  <apex:form >
    <apex:PageMessages id="messages"/>
    Click on Lookup to select a new account for this contact and then click on "Assign new account"
    <apex:pageBlock title="Contact Details">
      Contact name: {!c.name}
      <br/>
      <apex:pageBlockSection >
        <apex:inputText value="{!selectedAccountName}" id="accountName" label="Account"/>
        <a onclick="clearMessagesNow();popUp();" style="cursor: pointer;">Lookup</a>
        <apex:inputHidden value="{!selectedAccountId}" id="accountId"/>
         
        <script>
            var objInputName = '{!$Component.accountName}';
            var objInputId = '{!$Component.accountId}';
                   
            function popUp()
            {
              var objAccountInput = document.getElementById(objInputName);
              //alert('parameter is ' + document.getElementById(objInputName).value);
             
              var urlAdd = 'vf_AccountLookup_Controller';
              if(objAccountInput.value.length > 0)
              {
                urlAdd += '?srch=' + objAccountInput.value;
                //alert('urlAdd is ' + urlAdd);
              }
              var newWindow = window.open(urlAdd,'Popup','height=500,width=700,left=150,top=50,resizable=no,scrollbars=yes,toolbar=no,status=no');
            }
       
            function setAccount(recordId,recordName)
            {
              //alert('recordId is ' + recordId);
              //alert('recordName is ' + recordName);
              document.getElementById(objInputName).value = recordName;
              document.getElementById(objInputId).value = recordId;
            }
        </script>
        <br/>
        <apex:commandButton value="Assign new account" action="{!changeTheAccount}"/>
       
        <!--
          For clearing success/error message shown on the VF page after Lookup is clicked.
        -->
        <apex:actionFunction name="clearMessagesNow" action="{!clearMessages}"/>
       
      </apex:pageBlockSection>
    </apex:pageBlock>
  </apex:form>
</apex:page>
// The controller for the lookup popup box for selecting new account for a contact.
public class AccountLookup_Controller
{
    public String searchText {get;set;}
    public List<Account> searchResults {get;set;}
   
    public AccountLookup_Controller()
    {
        // get search parameter from url if present
        if(ApexPages.currentPage().getParameters().containsKey('srch'))
        {
            searchText = ApexPages.currentPage().getParameters().get('srch');
        }
        else
        {
            searchText = '';     
        }
        searchResults = [Select Id, Name, AccountNumber, Site From Account Where Name Like : searchText + '%'];
    }
   
    public void searchRecords()
    {
        searchResults = [Select Id, Name, AccountNumber, Site From Account Where Name Like : searchText + '%'];
    } 
}
<!--
  VF page name :- vf_AccountLookup_Controller
  The VF page for the lookup popup box which appears for selecting new account for a contact.
-->
<apex:page controller="AccountLookup_Controller" showHeader="false" sidebar="false">
  <apex:form >
    <script>
      window.onblur = function() {
          // close this popup window if it loses focus, that is, goes into the background
          self.close();
      }
      document.onblur = window.onblur;
      document.focus = window.focus;
    </script>
    <apex:pageBlock >
      <apex:sectionHeader title="Select the account to be associated with the contact"/>
      <apex:inputText value="{!searchText}" onkeyup="searchImmediately()"/> &nbsp;
      <apex:commandButton value="Go" action="{!searchRecords}" 
          rerender="results"/>
     
      <apex:actionFunction name="searchImmediately" action="{!searchRecords}" reRender="results"/>
     
      <apex:pageBlocksection title="Account Search Results" id="results">
        <apex:pageBlockTable value="{!searchResults}" var="a"
            rendered="{!searchResults.size>0}">
         
          <apex:column headerValue="Name">
            <a style="cursor:pointer;" 
                    onclick="window.opener.setAccount('{!a.Id}', '{!a.Name}');
                self.close();">
                {!a.name}
            </a>
          </apex:column>
         
          <apex:column headerValue="Account Number" value="{!a.AccountNumber}"/>
          <apex:column headerValue="Account Site" value="{!a.Site}"/>     
        </apex:pageBlockTable>
           
        <apex:outputText value="No results found"  
            rendered="{!searchResults.size=0}"/>
     
      </apex:pageBlocksection>
    </apex:pageBlock>
  </apex:form>
</apex:page>
Kalyani Jagdale 1Kalyani Jagdale 1
How can we create input button after clicking on the command button?
can anyone help me!!
Abhiraj DattaAbhiraj Datta
Hi Chamil,

Thanks for the above code. It was very helpful. Cheers!

Thanks,
Abhiraj
Jay reddyJay reddy

@Mohan Raj 33

Hello Mohan... I have the similar requirement but your code suits my requirement very well but can we just show few account fields directly instead of showing the list of account and choose accounts (I'm trying to have this code at account record level in a button - like a questionnaire form). Upon clicking on this button like your code does, it should show couple of field of that particular account record. And should able to do modification and able to save like your code does.

Your help is very much appreciated!

Many Thanks!