Twistleton Twistleton - 1 year ago 135
Scala Question

How can I validate fields in a table in Vaadin with Scala

How can I validate a field in a vaadin table? For example the year field with a regex:

val persons: BeanContainer[Int, Person] =
new BeanContainer[Int, Person] classOf[Person])

persons.addBean(new Person("Thomas", "Mann", 1929, 123123))
persons.addBean(new Person("W. B.", "Yeats", 1923, 643454))
persons.addBean(new Person("G√ľnter", "Grass", 1999, 743523))

// create table
val table: Table = new Table("Nobel Prize for Literature", persons)

table.setVisibleColumns(Array("id", "firstName", "lastName", "year"))

table.setColumnHeader("lastName", "last name")
table.setColumnHeader("firstName", "first name")
table.setColumnHeader("year", "year")

// create a validator
val yearValidator = new RegexpValidator("[1-2][0-9]{3}",
"year must be a number 1000-2999.");

// TODO check the year field!

I create a Regex Validator, but how can I set the validator to the right field?

Answer Source

You have to intercept the creation of the fields with a field factory and add the validators there:

    table.setTableFieldFactory(new DefaultFieldFactory() {
        public Field createField(Item item, Object propertyId, Component uiContext) {
            Field field = super.createField(item, propertyId, uiContext);
            if ("year".equals(propertyId)) {
                field.addValidator(new RegexpValidator("[1-2][0-9]{3}", 
                                   "year must be a number 1000-2999.");
            return field;

(Java, not Scala, but it should be straightforward to translate this to scala).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download