Set an initial label on element creation / replacement

Hey,
my goal is to set the element’s type as the initial element’s label at creation. The first solution I used was to listen on the shape.added event and set the label using modeling.updateLabel afterwards. However, this results in an additional event that is pushed to the commandStack (and a lot of other issues), which causes the undo function to skip over two steps to come back.
I wonder, if it is possible to set the label during the creation of an element inside the CustomPaletteProvider's startCreate function and the CustomContextPad's appendServiceTaskStart function in order to allow for one action for both events (e.g., elementFactory.create('shape', { type: 'bpmn:Task ', label: 'Task'})). Or does another solution for my desired behavior exist?
The same behavior is desired for replacing an element using the code retrieved from https://forum.bpmn.io/t/changing-task-to-usertask-by-code/1865/2.
Thank you in advance for any hint.

There are two ways of hooking into behaviors like element creation. You can hook into events and commands. Hooking into events that result from command execution and executing additional commands will leave these as separate commands on the command stack. Hooking into commands will allow you to execute additional commands that will not end up as separate commands. You can use a CommandInterceptor for that purpose.

Here’s an example:

class DefaultElementName extends CommandInterceptor {
  constructor(eventBus, modeling) {
    super(eventBus);

    this.postExecute("shape.create", ({ context }) => {
      const { shape } = context;

      const { id } = shape;

      modeling.updateLabel(shape, id);
    });
  }
}
1 Like

When I integrate it in the additionalModules, the event is called, but I get the error that modeling is undefined and thus the label is not updated.

Are you using the viewer or modeler?

Make sure to specify

DefaultElementName.$inject = [ 'eventBus', 'modeling' ];

to make sure that modeling is injected.

1 Like

Thank you very much. That’s the solution I was looking for.

1 Like