JavaScript onCancel Function Example


In this example, a user creates a lead, which has an activity child object. The administrator creates an onSave action so that whenever a lead is saved, a new activity screen opens. The onCancel function that is created prevents the user from cancelling an activity (such as a follow up call), if no other activity exists. As a result, a lead cannot be created without an associated activity. The following assumptions are made in this example:

  • The onSave code already exists, and it opens the activity object when a lead has been saved.
  • The activities have a Module ID of 7.


The typical structure of an onCancel query is as follows:

function fieldsOnCancel(){ return "moduleid.count"; }
function onCancel(count){
	if(count <= 0){
		window.location = "Melt://showAlert/message to display to the user"; return false;
	}else{
		return true;
	}
} 


An example of a complete onCancel query with header and footer information is as follows. This is placed in the Activities Module:

<html><head><title>onCancel</title><script type="text/javascript"> 
 
function fieldsOnCancel(){ return "7.count"; }
function onCancel(count){
	if(count <= 0){
		window.location = "Melt://showAlert/You can not cancel this record, at least one Activity record is required for this Lead";
		return false;
	}else{
		return true;
	}
}
</script></head><body></body></html> 



where:

  • function fieldsOnCancel() { return "moduleid.count"; } defines which module to count. To check the number of activity modules (module ID 7) associated with the current Lead and replace the module number with 7, the code used in the onCancel example is as follows:
function fieldsOnCancel() { return "7.count"; }
  • The command function onCancel(count) names the result and gives the result the name count.


The conditional query { if(count <=0) defines what to check for. In this case, to check if the count (that is, the number of other activity modules) is less than or equal to zero. Because this is the start of a conditional query, a left brace { is inserted at the beginning of the command.
If the condition is met, then two commands are performed: a message is displayed to tell the user why the user cannot cancel record creation, and a False result is returned preventing the user from using the Cancel button. The commands are included inside braces {}, and separated by a semicolon in the onCancel example as follows:

{
if(count <= 0){
	window.location = "melt://showAlert/ You can not cancel this record, at least one Activity record is required for this Lead "; 
	return false;
} 

 

Otherwise the code below defines what happens if the conditional query is not met (that is, when other activities exist), and allows you to cancel creating the current activity. 

else{ return true; }
}


A right brace } closes the conditional query, and the footer follows.