Search code examples
javawicketwicket-1.6dropdownchoice

How to get selected value in Wicket DropDownChoice?


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?


Solution

  • 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.