Search code examples
javawicketwicket-6

Wicket: hide a component without having to add all its children


I've been doing a project in Wicket, and I often find myself in an annoying situation. Let's say I have a piece of markup that I only show when some condition applies, like the following example:

<div wicket:id="myContainer">
    <div wicket:id="label1"></div>
    <div wicket:id="label2"></div>
    <div wicket:id="label3"></div>
    <div wicket:id="label4"></div>
</div>

and in my Java code:

WebMarkupContainer myContainer = new WebMarkupContainer("myContainer");
add(myContainer);

if(myDataObject != null){
    myContainer.add(new Label("label1", myDataObject.getData1());
    myContainer.add(new Label("label2", myDataObject.getData2());
    myContainer.add(new Label("label3", myDataObject.getData3());
    myContainer.add(new Label("label4", myDataObject.getData4());
} else{
    //HAVING TO DO THIS IS ABSURD!
   myContainer.add(new Label("label1", "");
   myContainer.add(new Label("label2", "");
   myContainer.add(new Label("label3", "");
   myContainer.add(new Label("label4", "");
   myContainer.setVisible(false);
}

As you can see, I'm forced to add dummy components to the container even in the cases where I'm not gonna show it, otherwise Wicket will throw an exception, saying I have components in the markup that I haven't added in code.

To me, this is ridiculous, having to instantiate extra components that I'm not gonna show is wasteful, time-consuming and makes the code less readable unnecessarily.

I'm hoping that it's just my ignorance of Wicket and that someone can tell me a method that allows me to "discard a component and all children".


Solution

  • I don't have time to try it right now but I'm pretty sure that

    } else{
      myContainer.setVisible(false);
    }
    

    should work. Wicket won't complain that children are missing if the parent component is not rendered at all.