Server

HOWTO: Modify a Workflow Variable outside of Workflow Context

Updated: December 19, 2024

A workflow (route instance) is stored in Nuxeo as a document of type "DocumentRoute". A node in the workflow is stored as a document of type "RouteNode". Both workflow and node variables are persisted on the workflow and node documents.

If you want to modify these variables outside of the workflow context (from a listener for example), you have to fetch the workflow instance document and you can use the available methods on their adapters, GraphRoute and GraphNode:

void setVariables(Map<String, Serializable> map);
Map<String, Serializable> getVariables();

e.g.

GraphRoute route = doc.getAdapter(GraphRoute.class);
GraphNode node = route.getNode(nodeId);

You can either listen to events triggered on the document following the workflow, or on workflow events. In the first case, in the event handler you have the document following the workflow and you have to get the workflow instance document. Use the following method on the DocumentRoutingService service:

List<DocumentRoute> getDocumentRoutesForAttachedDocument(CoreSession session, String attachedDocId)

For the second case, the workflowTaskCompleted event is triggered during a workflow every time a task is completed. On this event, the id of the workflow (route) instance documents is directly added into the map holding the properties of this event. Here is some sample data fetched with my debugger on a break point on TaskEventNotificationHelper notifyEvent method:

event: workflowTaskCompleted
eventProperties:
{category=eventDocumentCategory, sessionId=default-6778825317969559609, recipients=[Administrator, Administrator, test],
comment=szss, repositoryName=default, taskInstance=org.nuxeo.ecm.platform.task.TaskImpl@65fff289, documentLifeCycle=project}

((org.nuxeo.ecm.platform.task.TaskImpl)eventProperties.get("taskInstance")).getVariables()
taskVariables: {createdFromTaskService=true, taskNotificationTemplate=myTemplate, document.routing.step=0be590a5-8d03-48ef-9649-a82f06d8001a,
nodeId=Taska2e, documentRepositoryName=default, routeInstanceDocId=d05b14e4-8d60-41be-bea2-0d4063196c0b, directive=Aknowledgement, validated=false,
documentId=5b09103d-2fe1-40de-8737-a64b49425a6e}

So if you want to set a workflow variable from a listener listening to workflowTaskCompleted event:

  1. Get the taskInstance from the eventProperties map.
  2. Get the workflow document (using his id = "routeInstanceDocId") from the taskVariables.
  3. Adapt the document to GraphRoute.
  4. Use setVariables like in the first example.