How to add a BoundaryEvent to an UserTask programmatically

I would like to programmatically add a BoundaryEvent to an UserTask when user clicks a certain button on the page but I cant seem to make this work.

Here is what I am doing right now:

// Create the businessObject for BoundaryEvent
var timerEventDefinition = moddle.create("bpmn:TimerEventDefinition");
var boundaryEvent = moddle.create("bpmn:BoundaryEvent"); = "randomId";
boundaryEvent.attachedToRef = userTaskElement.businessObject;
boundaryEvent.eventDefinitions = [timerEventDefinition]; 

// Create BoundaryEvent shape and draw it on canvas 
var attrs = {
	businessObject: boundaryEvent,
	collapsed: false,
	height: 36,
	type: "bpmn:BoundaryEvent",
	width: 36,
	x: userTaskElement.x,
	y: userTaskElement.y
var boundaryEvenShape = elementFactory.createShape(attrs);
canvas.addShape(boundaryEvenShape, parentProcess);

This actually draws the BoundaryEvent on top of the UserTask element but if I move the UserTask the BoundaryEvent element is not moving with it as if they are not linked.

Can anyone help?

Hi @ThePasko,

check out this test case following this approach should make it work.

Adding to @FaHinse’s answer:

In general you should try to use higher level APIs exposed by Modeling to model on the diagram programmatically. This allows a user to redo / undo the changes and will correctly apply various behaviors, such as the attach behavior.

In this particular case use Modeling#createShape with the additional hint { attach: true }:

var task = ...;
var attachPosition = ...;

var newEvent = modeling.createShape(
  { type: 'bpmn:IntermediateThrowEvent' }, 
  { attach: true }