質問

So I am experiencing some odd behaviour using Vaadin 7 and the ComboBox component. Essentially, what is happening is that when it first renders the form, it appears to neither have selected the null selection nor any of the items added.

I have attempted to recreate this behaviour with the following code and this demonstrates the issue.

@Override
protected void init(VaadinRequest request) {

    final FieldGroup binder;

    FormLayout form = new FormLayout();
    form.setMargin(true);

    setSizeFull();
    setContent(form);

    final Label output = new Label();
    form.addComponent(output);

    ComboBox box = new ComboBox("My Dropdown");

    final PropertysetItem fields = new PropertysetItem();
    fields.addItemProperty("country", new ObjectProperty<String>(""));
    binder = new FieldGroup(fields);
    binder.bind(box, "country");

    box.addItem("aus");
    box.setItemCaption("aus", "Australia");

    box.addItem("uk");
    box.setItemCaption("uk", "United Kingdom");

    box.setRequired(true);
    box.setImmediate(true);
    box.setRequiredError("Country is required field");

    Button submit = new Button("Submit", new ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            try {
                binder.commit();
                output.setValue((String) fields.getItemProperty("country").getValue());
            }
            catch (CommitException e) {
                Notification.show("fail!");
            }
        }
    });

    form.addComponent(box);
    form.addComponent(submit);
}

By default the ComboBox has allow null selection set to true. So there is a blank entry, which represents a null value selection. However the ComboBox's value when first rendered neither represents the null selection nor one of the items but an empty string.

So when I load the form and click the button the outcome is neither a failure, which it should be because I haven't selected anything yet, nor one of my selections.

This is causing an issue for me in a more advanced UI application but very much the same thing going on here.

Could anybody enlighten me as to what is happening here?

Many thanks,

Joe

役に立ちましたか?

解決

So when I load the form and click the button the outcome is neither a failure, which it should be because I haven't selected anything yet, nor one of my selections.

Combobox is not empty as you think. It has default property value, that you set as empty string:

fields.addItemProperty("country", new ObjectProperty<String>(""));

Thus form pass validation, because empty string is also a value and empty string != null.

Change this row:

fields.addItemProperty("country", new ObjectProperty<String>(""));

to:

fields.addItemProperty("country", new ObjectProperty<String>(null, String.class));
box.setNullRepresentation("-- Select Country --");
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top