Create a label programmatically

Hello guys!

I’ve got another question - is there a way, and I’m sure it is, to create a shape along with a label?
I’m assuming I could use elementFactory.createLabel but what should I pass as a businessObject then and how to link them together?

Thank you in advance!
p.s. The more I dive into bpmn-js and diagram-js the more I see how cool it is.

What’s also possible is to use the modeling.updateLabel API to set the label after the element was created.

const modeling = modeler.get('modeling');

const shape = modeling.createShape({ type: 'bpmn:Task'}, {x: 200, y: 300 }, parent);

modeling.updateLabel(shape, 'foo');

Thank you!

I’m assuming I can not inject modeling into my Pallete class?
… but I can implement my own Updater which is looks like overkill in this scenario.

So maybe I can create label some how with elementFactory within Pallete class?

Alright, I can inject modeling into Pallete, but I can’t use modeling.updateLabel on that step just because there is no actual element yet on a canvas so it can’t be updated.

maybe we’ve got another approach?

What kind of element are you trying to create? Maybe it’s just sufficient to set the name property when creating the element, the label should be automatically created.

Thank you Niklas.

I was trying to create a bpmn:Participant and bpmn:StartEvent elements.
and I’ve made an attempt to pass a name prop to factory method with no luck :frowning:

here is a code snippet that doesn’t work

      const participant = elementFactory.createParticipantShape({
        width: 300,
        height: 204,
        name: "Device",
        businessObject: businessObject,
      });

      const sdi0 = elementFactory.createShape({
        type: 'bpmn:StartEvent',
        x: 40,
        y: 8,
        name: "sdi0",
        parent: participant
      });

Yay, I’ve got it working. Thank you Niklas for pushing me in a right direction, also a huge help was that post.
It appears that passing the name property itself doesn’t work. What you want to do instead is to set the name prop for a businessObject of a shape.
Here is an example:

      const sdi0 = elementFactory.createShape({
        type: 'bpmn:StartEvent',
        x: 40,
        y: 8,
        parent: deviceContainer
      });
      sdi0.businessObject.name = "in";

1 Like