Javascript confirm alert popup using Visualforce page and Apex Class

Below is the example of how to generate the confirm alert popup using Visualforce page and Apex Class.

in the  commandLink onClick method executes before the action method, and if returns true then controller action is executed.
Note:
commandLink onClick is return as false if the user clicks cancel, then controller action is not fired and still in the same VF Page.

Visualforce Page:

<apex:page standardController=”Contact” extensions=”extContact” showHeader=”false” standardStylesheets=”false” sidebar=”false”>
<script type=”text/javascript”>
function confirmDeactivate() {
return confirm(‘Are you sure you want to Deactivate Contact?’);
}
</script>
<apex:form >
<div style=”{!if((msg != ‘d’),’display:none’,’color:red;font-weight:bold;text-align:center;’)}”><font color=”red”>Deactivated Successfully!</font></div>
<apex:commandLink action=”{!deactivateContact}” onClick=”if (!confirmDeactivate()) return false;” reRender=”myPageBlock”>Deactivate Contact
</apex:commandLink>
</apex:form >
</apex:page>

Here confirmDeactivate javascript is prompt when the clciking the Deactivate Contact link, if selected as OK, then Apex controller (deactivateContact) is fired, if Cancel then the Apex Controller is not fired.

Javascript Popup
Javascript Popup

Apex Controller Class:

public with sharing class extContact {
public string Id {get;set;}
public string msg {get;set;}
public Contact C;

ApexPages.StandardController GstdController;
public extContact(ApexPages.StandardController controller) {
msg =’a’;
msg = (string)Apexpages.currentPage().getParameters().get(‘msg’);
Id = (string)Apexpages.currentPage().getParameters().get(‘id’);
GstdController=controller;
this.C= (Contact)GstdController.getRecord();
}

public PageReference deactivateContact() {
msg = (string)Apexpages.currentPage().getParameters().get(‘msg’);
C.Status__c = ‘Deactivated’;
update C;

PageReference redirect = new PageReference(‘/apex/vfContact?id=’+id’+’msg=d’);
redirect.setRedirect(true);
return redirect;
}
}

Written by 

Salesforce MVP | Lightning Champion | 17x Salesforce Certified | Application Architect | 7x Trailhead Ranger | Techforce Services | Australia

Leave a Reply

Your email address will not be published. Required fields are marked *

*