Search code examples
javawicket

Adding dynamic element ids to the dom in Wicket


I have a repeating view with a container inside. Also, I added elements with behaviors to this container.

RepeatingView listItems = new RepeatingView("listItems");
    listItems.setOutputMarkupId(true);
    listItems.setRenderBodyOnly(true);
    for (int i = 0; i < typeList.size(); i++) {
        WebMarkupContainer container = new WebMarkupContainer(listItems.newChildId());
        container.setOutputMarkupId(true);
        Label typeLabel = (Label) new Label("typeLabel" + i, "label");
        container.add(typeLabel);
        container.add(createMultiChoiceForCustomType("choice" + i, i));
        listItems.add(container);
    }
    add(listItems);

and HTML

<div class="otherPermissionsOption">
      <div wicket:id="listItems"></div>
</div>

and I've got an error in the console

Wicket.Ajax: Cannot bind a listener for event "change.select2" on element "id13c" because the element is not in the DOM

How can I put dynamic container+elements ids on the HTML page to get rid of this error? Is it possible to have dynamic containers in Wicket?


Solution

  •  listItems.setOutputMarkupId(true);
     listItems.setRenderBodyOnly(true);
    

    These two lines contradict.

    listItems.setOutputMarkupId(true); says - I want Wicket to add id attribute to the HTML element and to generate unique value for it

    listItems.setRenderBodyOnly(true); says - I do not need the HTML element tag (will all its attributes). I want Wicket to render just the children components of this component. You need to remove it.

    Your markup should contain HTML elements for the children:

    <div class="otherPermissionsOption">
      <div wicket:id="listItems">
        <span wicket:id="typeLabel"></span>
        <div wicket:id="choice"></div>
      </div>
    </div>
    

    And there is no need to add + i to the component ids in the Java code.

    Also there is no need of casting at:

    ... = (Label) new Label("typeLabel" + i, "label");