ethanfar
ethanfar

Reputation: 3778

StringResourceModel only works for label

I was trying to create a link with the username on it (i.e. dynamic data), and couldn't manage to get the StringResourceModel to work with a Link.
My code looked something like:

Properties:

some.key=User name is: {0}

Java:

StringResourceModel model = 
    new StringResourceModel("some.key", this, null, new Object[] { getUserName() }); 
add(new Link("someid", model) {
    @Override
    public void onClick() {
        // do something ...
    }
});

HTML:

<a wicket:id="someid">some text to replace</a>

However, that didn't work, i.e. the text was never replaced.

I tried a different direction, which did work, and looks something like this:

Java:

StringResourceModel model = 
    new StringResourceModel("some.key", this, null, new Object[] { getUserName() }); 
Link link;
add(link = new Link("someid") {
    @Override
    public void onClick() {
        // do something ...
    }
});

link.add(new LabeL("anotherid", model));

HTML:

<a wicket:id="someid"><span wicket:id="anotherid">some text to replace</span></a>

(the properties file is the same).

My question is, am I right to assume that the StringResourceModel doesn't work with Links (I call this an assumption since I didn't see anything about this in the JavaDOC) ?
If not, how can the StringResourceModel be used directly with the Link, without the mediator Label ?

Upvotes: 0

Views: 440

Answers (2)

Christophe L
Christophe L

Reputation: 14035

The model parameter in the Link constructor isn't meant to be used as a display value. To set the text of the link you need to explicitly add a Label to it:

Link<Void> link = new Link<Void>("link");
link.add(new Label("label", model);
add(link);

and in HTML:

<a wicket:id="link"><span wicket:id="label"></span></a>

The model in the constructor is meant to be used in the onclick method (or similar). For example (from the JavaDoc):

IModel<MyObject> model = ...;
Link<MyObject> link = new Link<MyObject>("link", model) {
    public void onClick() {
        MyObject obj = getModelObject();
        setResponsePage(new MyPage(obj));
    }
};
add(link);

Upvotes: 2

Nicktar
Nicktar

Reputation: 5575

In your first example, you aren't telling wicket to replace the text. You just apply a model to the link without telling wicket what to do with it. To fix this, you'd need to replace your HTML with something along the lines of

<a wicket:id="someid"><wicket:message key="some.key">some text to replace</wicket:message></a>

I don't remember the syntax completely and can't try this right now but it should help you anyway.

Upvotes: 0

Related Questions