Wednesday, November 19, 2008

It's Just That Easy

A little Wicket . . . .

The examples I find that implement a Wicket dropdown choice have too much additional complexity. I want to see the basics. Here's the basics.

The easy way to get this running is to run
mvn archetype:generate 
and select the Jetty project. Add the Wicket dependency to the pom.xml. Create the form, the backing Java class and the WicketApplication class as shown here.

<html>
<body>
  <form wicket:id="form" name="form">
    <select wicket:id="ddc" name="ddc">
      <option value="1">choice1</option>
      <option value="2">choice2</option>
    </select>
  </form>
</body>
</html>
package com.availity.hr;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.markup.html.form.DropDownChoice; 
import org.apache.wicket.markup.html.form.Form; 

import java.util.List;
import java.util.Arrays;
 
public class Page extends WebPage {
   private List letters = Arrays.asList(new String[] { "A", "B", "C" });
   //public String selected = "B";
 
   public Page() {
     Form form = new Form("form");
     add(form);
     DropDownChoice choice=new DropDownChoice("ddc", 
                              //new PropertyModel(this, "selected"), 
                              letters);
     form.add(choice);
   }
}
In the code above, uncomment the field and the PropertyModel parameter to cause the rendered dropdown choice to present a default value. The code as shown will present 'Choose One' in the dropdown.
package com.ez.hr;
 
import org.apache.wicket.protocol.http.WebApplication;
 
public class WicketApplication extends WebApplication {    
 
 public WicketApplication() { }
  
 public Class getHomePage() {
  return Page.class;
 }
}
To see the resulting webpage with its dropdown, run
mvn compile jetty:run 
and navigate your browser to
http://localhost:8080/project
where 'project' is the name used in the maven create step.

This is the basics for DropDownChoice but, there is a problem with it. When run, the list is stored in the user's session, an unnecessary use of memory. Wicket's LoadableDetachableModel corrects this, allowing the data to be stored in the application context instead of the user's session. Override the load() method of LoadableDetachableModel and return the list (in our example, the list of letters). Finally, pass this instance of LoadableDetachableModel to the DropDownChoice constructor instead of the list of letters. For more on the LoadableDetachableModel class, see the ServerSide article.

Wicket's IChoiceRenderer allows objects other than Strings to be passed to the DropDownChoice.