javahtmlwicketwicket-1.5

How to add a component to a label?


I have the following html:

<label wicket:id="drugSearchResult.row.item.label" for="drug_1">[Drug XYZ]  
    <span wicket:id="drugSearchResult.row.item.info">[Information, Price, Other]</span>
</label>

But label element are not allowed to add a child component. Is there any way to achieve this html requirement?

This is the designer's requirement:

Drug XYZ // label
Information, Price, Other // span


Solution

  • Make sure you're using FormComponentLabel for the <label> element instead of Label.

    Label's purpose is to output text inside the associated element (it can be a <span>, <div> or almost any other tag).

    FormComponentLabel's purpose is to model <label> tags. They receive the FormComponent they're related to and automatically output the for attribute with the proper value for the dom id attribute.

    Take a look at the Wicket wiki page on Form control labels. They're adding components to FormComponentLabel there.

    If you'd like to avoid using FormComponentLabel at all, you shouldn't be giving it a wicket:id attribute, and manually set the DOM id attribute of the element the <label> is going to refer to. Then just use it in the for attribute of the <label>.

    For instance:

    HTML

    <input wicket:id="drug">
    <label for="drug_1">[Drug XYZ]  
        <span wicket:id="drugSearchResult.row.item.info">[Information, Price, Other]</span>
    </label>
    

    Java

    TextField drug = new TextField("drug");
    drug.setMarkupId("drug_1"); // Make sure this ID is unique in the page!
    drug.setOutputMarkupId(true);
    add(drug);
    Label drugDescription = new Label("drugSearchResult.row.item.label", aModel);
    add(drugDescription);