Search code examples
comboboxvaadinvaadin7

is it possible to sort ordinary combobox when I add new item? (vaadin)


I have a combobox.. and when I add a new item there, it has to be on the top of the list.. how is it possible to add this item on the top?

or, just to try to sort this list in alphabetical order when new item has been added?


Solution

  • 1.

    how is it possible to add this item on the top?

    You can supply your own datasource and use it to always insert items on position 0, something along the lines of:

        TextField input = new TextField("New person name");
        BeanItemContainer<Person> comboDataSource = new BeanItemContainer<>(Person.class);
        ComboBox combo = new ComboBox("Persons", comboDataSource);
        combo.setItemCaptionPropertyId("name");
    
        layout.addComponent(input);
        layout.addComponent(combo);
        layout.addComponent(new Button("Add", new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent clickEvent) {
                comboDataSource.addItemAt(0, new Person(input.getValue()));
            }
        }));
    

    2.

    try to sort this list in alphabetical order when new item has been added

    Call the sort(Object[] propertyId, boolean[] ascending) method on your container after adding items.