William S
William S

Reputation: 33

How to set value to default choice in Wicket DropDownChoice

I need to create a wicket dropdownchoice component, I can replace default "Choose One" text to "All" by set

nullValid=All
null=All

in its properties file. I also want to set the value of "All" to -1, but could not get it done.

<select>
<option selected="selected" value>All</option>
<option value="1">Not Started</option>
<option value="2">In Progress</option>
<option value="3">Complete</option>
</select>

what i want is

<select>
<option selected="selected" value="-1">All</option>
<option value="1">Not Started</option>
<option value="2">In Progress</option>
<option value="3">Complete</option>
</select>

Upvotes: 3

Views: 5744

Answers (2)

soorapadman
soorapadman

Reputation: 4509

I'm not sure whether you got martin point . I am going to give some simple solution which will resolve your issue. let's assume you have SelectionOption class which you have key and value

public class SelectOption {
    private String key;
    private String value;

    public SelectOption(String key, String value) {
        this.key = key;
        this.value = value;
    }
     // getter and setter
}

Create a simple list of selectOptions and pass to the dropdownchoice

List<SelectOption> selectOptions = new ArrayList<>();
        selectOptions.add(new SelectOption("-1","ALL"));
        selectOptions.add(new SelectOption("1","Not Started"));
        selectOptions.add(new SelectOption("2","In Progress"));
        selectOptions.add(new SelectOption("3","Completed"));

//Simply override choiceRender option to show key and value . I have override getDefaultChoice to remove select one(Its my convenient) since you removed already .

        add(new DropDownChoice("selectOption", selectOptions,new ChoiceRenderer<SelectOption>("value","key"){
            @Override
            public Object getDisplayValue(SelectOption object) {
                return object.getValue();
            }

            @Override
            public String getIdValue(SelectOption object, int index) {
                return object.getKey();
            }
        }){
            @Override
            protected CharSequence getDefaultChoice(String selectedValue) {
                return "";
            }
        });

Output:

<select wicket:id="selectOption" name="selectOption">
<option value="-1">ALL</option>
<option value="1">Not Started</option>
<option value="2">In Progress</option>
<option value="3">Completed</option>
</select>

Upvotes: 1

martin-g
martin-g

Reputation: 17503

For this you have to setup the DropDownChoice to not allow null value and add -1 to your list of allowed/possible values. Finally you have to instantiate it with: new DropDownChoice("compId", Model.of(-1), Arrays.asList(-1, 1, 2, 3), choiceRenderer), i.e. -1 should be set as the default model object, so it is selected in the markup.

Upvotes: 3

Related Questions