Workflow scripted elements, actions, and policies require scripting examples of common workflow tasks. You can cut, paste, and adapt these examples into your scripted elements.

Return All Workflows Run by the Current User

The following JavaScript example obtains all workflow runs from the server and checks whether they belong to the current user.

var allTokens = Server.findAllForType('WorkflowToken');
var currentUser = Server.getCredential().username;
var res = [];
for(var i = 0; i<res.length; i++){
	if(allTokens[i].runningUserName == currentUser){
	  res.push(allTokens[i]);
	}
}
return res;

Access the Current Workflow Token

You can access the current workflow token by using the workflow variable. It is an object of type WorkflowToken that provides access to the current workflow run. The following JavaScript example gets the ID of the workflow token and its start date.

System.log("Current workflow run ID: " + workflow.id);
System.log("Current workflow run start date: "+workflow.startDate);

Schedule a Workflow

The following JavaScript example starts a workflow with a given set of properties, and then schedules it to start one hour later.

var workflowToLaunch = myWorkflow ;  
// create parameters 
var workflowParameters = new Properties() ;
workflowParameters.put("name","John Doe") ;
// change the task name 
workflowParameters.put("__taskName","Workflow for John Doe") ; 

// create scheduling date one hour in the future
var workflowScheduleDate = new Date() ; 
var time = workflowScheduleDate.getTime() + (60*60*1000) ;
workflowScheduleDate.setTime(time) ; var scheduledTask =
workflowToLaunch.schedule(workflowParameters,workflowScheduleDate);

Run a Workflow on a Selection of Objects in a Loop

The following JavaScript example takes the array of virtual machines and runs a workflow on each one in a For loop. VMs and workflowToRun are workflow inputs.

var len=VMs.length;
for (var i=0; i < len; i++ )
{
 var VM = VMs[i];
 //var workflowToLaunch = Server.getWorkflowWithId("workflowId");
 var workflowToLaunch = workflowToRun;
 if (workflowToLaunch == null) {
 throw "Workflow not found";
 }
var workflowParameters = new Properties();
workflowParameters.put("vm",VM);
var wfToken = workflowToLaunch.execute(workflowParameters);
System.log ("Ran workflow on " +VM.name);
}