wicketwicket-6

Hide a fiedset HTML element with Wicket


I have a fieldset element in my HTML page that I want to hide under some conditions.

I usually hide labels like this.

HTML file

<label class="optional"><wicket:message key="myLabel" /></label>

JAVA file

Label myLabel = new Label("myLabel", new ResourceModel("my.label"));
if (true) {
   myLabel.setVisible(false);
}

How do I hide this?

HTML file

<fieldset class="field_set">
    <legend>
        <wicket:message key="anotherLabel"/>
    </legend>
</fieldset>

Thank you very much!


Solution

  • The simplest way is to have a Java component for the fieldset too:

    WebMarkupContainer fieldset = new WebMarkupContainer("fieldsetId");
    add(fieldset);
    fieldset.add(new Label("anotherLabel", ...));
    ...
    if (condition) {
       fieldset.setVisible(false);
    }
    
    
    <fieldset class="field_set">
        <legend>
           <wicket:container wicket:id="anotherLabel"/>
        </legend>
    </fieldset>
    

    If you want the Label to control the visibility of the fieldset then instead of WebMarkupContainer you could use EnclosureContainer

    Label label = new Label("anotherLabel", ...);
    EnclosureContainer fieldset = new EnclosureContainer("fieldsetId", label);
    add(fieldset);
    fieldset.add(label);
    ...
    if (condition) {
       label.setVisible(false);
    }
    

    Note: I've changed your usage of <wicket:message> with <wicket:container> because wicket:message is the no-Java version of new Label(id, new ResourceModel(key)). You should use one or the other. The Java version should be used when you need more control, like in your case to control the visibility. wicket:container can be used when you want to Wicket to render just the textContent without any HTML element. If you don't care about having an HTML element then you can just use <span> instead.