Connecting a Vaadin SQL Container to a Combo Box
It must be me. But I spent a lot of time trying to figure out how to connect a database table implemented as a Vaadin SQL Container to a Vaadin Combo Box.
It seems such a simple concept.
Anyway, here was my requirement.
I needed a combo box to contain a list of Australia suburbs. The user would select a suburb which would filter the results in a table on the screen.
My database table was very simple.
A id field ( which was the primary key ) and a name field which contained the suburb name.
The code for the SQL Container was simple.
TableQuery q = new TableQuery("suburb", connectionPool);
suburbContainer = new SQLContainer(q);
Now code to establish the combo box and links to the SQL Container.
ComboBox suburbCB = new ComboBox();
suburbCB.addItem("");
suburbCB.setCaption("Filter by Suburb");
suburbCB.setContainerDataSource(app.getDatabase().loadSuburbs());
suburbCB.setItemCaptionPropertyId("name");
suburbCB.setItemCaptionMode(AbstractSelect.ITEM_CAPTION_MODE_PROPERTY);
// Set a reasonable width
suburbCB.setWidth(350, UNITS_PIXELS);
// Set the appropriate filtering mode for this example
suburbCB.setFilteringMode(Filtering.FILTERINGMODE_STARTSWITH);
suburbCB.setImmediate(true);
Some explanation is required.
- Create the combo box
- Set the data source as the SQL Container. ( this comes back from the loadSuburbs() method )
- Set the Item Caption Property Id - this "stumped" for a long time. This method takes the field ( or property ) from the SQL Container that you want displayed in the Combo box. If you don't set it you get the "id" property displayed.
- Set a filtering mode. The "starts with" mode allows the user to start entering the name of the suburb in the combo box and the data is filtered on the user input.
Seems easy when you know how.
Comments
Post a Comment