JavaScript onPreSave Function Example 1: Checking a Single Condition


In the data source, there may be validation rules in place which must be replicated in the Swift MEAPâ„¢ application. In an Activity for example, the Planned Start Time must be before the date that the Activity is due (Due field). Both fields are stored in the current object (Activity). In this example, the following assumptions are made:

  • The MEFIELDNAME of the Due field is TASKDT01.
  • The MEFIELDNAME of the Planned Start Time field is TASKDT02.


The typical structure of an onPreSave query, which checks a single condition, is as follows:

function fieldsOnPreSave(){ return "MEFIELDNAME,MEFIELDNAME"; }
function onPreSave(value1,value2) { 
	if( value1 > value2 ) { 
		return true; 
	}else{ 
		window.location = "melt://showAlert/message to display"; 
	return false; 
	}
} 



An example of a complete onPreSave query with header and footer information, which checks a single condition, is as follows:

<html><head><title>PreSaveExample1</title><script type="text/javascript"> 
function fieldsOnPreSave(){ return "TASKDT01,TASKDT02"; }
function onPreSave(due,planned){ 
	if( due > planned ) {
		return true; 
	}else{ 
		window.location = "melt://showAlert/$due.greater.than.planned"; 
		return false; 
	}
}
</script></head><body></Body></html> 


where:
function fieldsOnPreSave(){return "MEFIELDNAME,MEFIELDNAME";} specifies which fields to check. To replace the two MEFIELDNAMEs with the IDs of the fields that are read, the code in onPreSave example 1 is as follows:

function fieldsOnPreSave(){return "TASKDT01,TASKDT02";} 


function onPreSave(value1,value2) names the two fields that are read. The (value 1, value 2) fields are replaced with the names (due, planned). The fields are named in the order that they are defined in the fieldsOnPreSave() command:

function onPreSave(due,planned) 


A left brace { starts the query to check whether the due date is greater than the planned date as follows:

{if(due > planned) 


{return true;} defines what to do if the query (due date is greater than planned date) is correct. In this example, the user is allowed to save the record if the due date is greater than the planned date.
The else command defines what to do if the condition (due date is greater than planned date) is not correct. In this example, a message is displayed using the window.location command, and a False value is returned preventing the user from saving the record.

A custom device message is defined by inserting the dollar symbol ($) after the showAlert: command, and a new message must be created as shown in "Custom Device Messages and Multiple Language Installations".

The code in onPreSave example 1 is as follows:

else{window.location = "melt://showAlert/$due.greater.than.planned"; return false;
} 


A right brace } signals the end of the IF query.