How to get selected value in Wicket DropDownChoice?

5.7k views Asked by At

In wicket form I have a DropDownChoice, and I want to take a selected value in it. I have:

private final List<DimSpecific> specificList;
private DimSpecific specificPtr = null;
...
specificList = roles.getSpecificList();
specificPtr = new DimSpecific();
DropDownChoice specific = new DropDownChoice("specific", new Model<>(specificPtr), specificList, new ChoiceRenderer<DimSpecific>("code", "id"));
Form form = new Form("frm_0_07"){
    @Override
    protected void onSubmit() {
        String specificSelected = specificPtr.getCode();
    }
}

And the variable specificSelected equals to null. How I can get selected value?

2

There are 2 answers

0
Dan Alvizu On BEST ANSWER

Have you added DropdownChoice to the form?

The model object you pass in will be updated - not the object itself. In your case it is an unassigned variable (new Model<>(specificPtr)) so you can't read from it.

Try this:

private final List<DimSpecific> specificList;
private DimSpecific specificPtr = new DimSpecific(); // or init to some default value
private IModel<DimSpecific> dropdownModel = new PropertyModel<DimSpecific>(this, "specficicPtr");
...
specificList = roles.getSpecificList();
DropDownChoice specific = new DropDownChoice("specific", dropdownModel , specificList, new ChoiceRenderer<DimSpecific>("code", "id"));
Form form = new Form("frm_0_07"){
    @Override
    protected void onSubmit() {
        String specificSelected = dropdownModel.getObject();
    }
}

This will also make the specificPtr equal to the selected value - the reason is that PropertyModel tells the dropdownchoice where to setObject() for the selected dropdown on submit - into specificPtr.

0
Alisher Gulov On

Try this:

List<DimSpecific> list = getList(); //not importent
Model<DimSpecific> dimSpecificModel = new Model<DimSpecific>();
ChoiceRenderer<DimSpecific> choiceRenderer = new ChoiceRenderer<>("code", "id");
DropDownChoice<DimSpecific> choice = new DropDownChoice<DimSpecific>("specific", dimSpecificModel, list, choiceRenderer);

Button button = new Button("button", Model.of("")){
    @Override
    public void onSubmit() {
        System.out.println(dimSpecificModel.getObject());
    }
};