SpiderRico
SpiderRico

Reputation: 2026

Changing the textfield of button on submit in Wicket

I've a simple button in my panel defined as the following:

item.add(new Button("favButton") {
                public void onSubmit() {
                    User.getCurrentUser().fav(book); 
                }
       });

The button looks like this in the html file:

<td><button type="submit" class="btn btn-default" wicket:id = "favButton">Add to my favourites</button></td> 

So, by default its text is:

Add to my favourites

I want it to change to the following after its clicked:

Remove from my favourites

and back to the previous one(Add to my favourites) if its clicked in this state.

I already keep the state of the button in a variable so, how can I change the label of the button according to that variable ?

EDIT:

Changed it to the following after svenmier's suggestion:

Panel.java

.....
IModel<String> textModel = new AbstractReadOnlyModel<String>() {
                public String getObject() {
                    return added ? getString("removeFav") : getString("addFav");
                }
            };
            final Form<?> buttonForm = new Form<Object>("buttonForm");

            buttonForm.add(new AjaxButton("favButton", textModel) {
                @Override
                protected void onSubmit(AjaxRequestTarget target,
                        Form<?> form) {
                    super.onSubmit(target, buttonForm);
                    target.add(this);

                }
            });
            buttonForm.add(new AjaxButton("readButton", textModel) {
                @Override
                protected void onSubmit(AjaxRequestTarget target,
                        Form<?> form) {
                    super.onSubmit(target, buttonForm);
                    target.add(this);

                }
            });
            item.add(buttonForm);
            ....

Panel.html

 <form action="" wicket:id="buttonForm">

               <td><input wicket:id="favButton" type = "submit"/></td>
               <td><input wicket:id="readButton" type = "submit" /></td>

              </form>

Still not working though.

Upvotes: 0

Views: 1647

Answers (1)

svenmeier
svenmeier

Reputation: 5681

Easiest solution is this:

  • use <input type="button"> instead
  • give the button a model

... so it automatically changes the value attribute:

IModel<String> textModel = new AbstractReadOnlyModel<String>() {
    public String getObject() {
        return added ? getString("removeFav") : getString("addFav");
    }
};
new Button("favButton", textModel) { };

Upvotes: 1

Related Questions