I am trying to display a pop-up alert with a message on the uncheck of checkbox. I am using Standard controller and need to implement this functionality on the Contact Page Layout. I have a custom checkbox field: Customer__c
(default unchecked).
What my requirement is that when I check this,it should save normally (this is happening) but when some user tries to uncheck it, that user should get a pop-up alert with the message.
I have created a VF page for the same and a controller class. I have placed the VF page on the Standard Contact Page Layout keeping the Height as 0. But whenever I uncheck and try to save the record, the pop-up doesn't show up. What am I missing in my code (I don't get any compile/debug errors).
Below is the code for VF:
<apex:page standardcontroller="Contact" rendered="{!(Contact.Customer__c)}" >
<script type="text/javascript">
var msg="Unchecking this box will imply that the user has churned and will automatically de-activate in the Admin Panel.If you dont want that to happen, kindly check the box again";
function throwalert{
if ( {!Contact.Customer__c} == false)
{
alert(msg); setAlertVal();
}
}
window.onclick = throwalert();
</script>
</apex:page>
This is the code for the controller:
public class PopUpAlert
{
public Contact cont;
public PopUpAlert(ApexPages.StandardController controller){
Contact cont = (Contact)controller.getRecord();
cont=[select id,Customer__c from Contact where Id=: cont.ID];
}
public void setAlertVal(){
cont.Customer__c = false;
update cont;
}
}
Best Answer
Since your original goal is prevent user uncheck the Customer__c flag on a Contact record, you can simple make the field disabled (read-only) on the page Layout. See Control User Access to Fields
Answer to the question "Why popup does not appear".
Please look at the code below:
When a VF page renders this part
{!Contact.Customer__c}
transforms intotrue
, since at the time of rendering this flag was actuallytrue
. When you uncheck this field, it does not change change in the part of of your JavaScript function because at this time you rendered VF page looks like:Possible solution.
Option 1. Unfortunately, there is no a simple way to add an event listener to the standard element on a standard page. Though you can try adding a listener to the Customer__c field from your VF page, and assign a handler that would show a popup each time the checkbox is unchecked.
Option 2. Create a custom VF page which is a full copy of you standard Contact Page. Here it would be easier to add event listeners to the fields.