Wicket - Submitting a form to an anchor position

Tuesday, 20 April 2010

I had a non-ajax style form on the bottom of a long page. When the form is submitted, the top of the page is displayed, and not the bottom. Annoying for a user if they've submitted a comment to a page for example, and they have to scroll down right to the bottom of the page to see if it's been added. In a standard form in HTML you can just submit the form to an anchor like this...
<form method="post" action="/myPage.html#jumpToHere">
... my form content ...
</form>

<div id="jumpToHere">
... Jump back to here once submitted
</div>
In Wicket you can do this by overriding the onComponentTag() method in your wicket Form...
public class MyForm extends Form<T>
{
   ...

   @Override
   protected void onComponentTag(ComponentTag tag)
   {
       super.onComponentTag(tag);
       StringBuilder b = new StringBuilder(tag.getString("action").toString()).append("#jumpToHere");
       tag.put("action", b.toString());
   }
}

2 comments:

Unknown said...

It is also possible to do this with Wicket's AttributeAppender:

Form form = new Form("form);
form.add(new AttributeAppender("action", new Model("#jumpToHere"), ""));

Eurig Jones said...

Markku - That's definitely the better way of doing it, you're right.