Setting new Process Variables Programtically [Java Api]

Hi,

I’m pretty new to Camunda and wanted to know how to set new process variables.

I start a process through ProcessInstance instance = runtimeService.startProcessInstanceByKey("MyProcess",); and wanted to set new Process Variables when a step / user task state was achieved. How can I do this? By the way I’m not using any forms.

Thanks in advance.

1 Like

Camunda has many good examples on github.

And, here are some additional examples of my own:

Adding either a single or many variables to the start of a process is straightforward:

Starting process with a single variable

ProcessInstanceWithVariables pVariablesInReturn = runtimeService.createProcessInstanceByKey(processID)
				.setVariable("hello", hello)
				.executeWithVariablesInReturn();

Getting that value back:

processVariableName.toString()
example...
hello.toString(); 

Starting process with multiple variables:

Map<String, Object> variables = new HashMap<String, Object>();

// note: fetching values from a JAX-RS post payload
for (final JsonNode jsonNode : arrNode) {
	variables.put(jsonNode.findValue("name").asText(), jsonNode.findValue("value").asText());
}

// start the process
ProcessInstanceWithVariables pVariablesInReturn = runtimeService.createProcessInstanceByKey(processID)
		.setVariables(variables)
		.executeWithVariablesInReturn();

And getting a VariableMap back:

VariableMap variableMap = pVariablesInReturn.getVariables();

Variables can also be added from within task implementations:
source

public void addProcessVariable(DelegateExecution execution) throws Exception {
		
	// yetAnotherProcessVariable = "foo";
	execution.setVariable("yetAnotherProcessVariable", "foo");

}

Ok thanks, I found out that you can set Variables over the runtimeService. This way knowing the process instance id as well you can set variables.