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;
}
}

(3387)

Written by 

I am Sakthivel Madesh, a certified Salesforce Developer & Administrator working on Salesforce Technology since 2011. I am currently working in IBM Austraila as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 10 Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply