Search code examples
javavaadinvaadin7

How can I Update item on Vaadin's Grid without putting explicitly all fields on it?


I try to create regular CRUD operations on Grid table for User entity - which is like this:

public class User {
    private id;
    private String name
    private Role role;
}

with appropriate getters and setters.

  • The Grid should have 2 fields: name and role.name.

  • I want to create a data IndexedContainerfor that Grid

  • I want to make updates - which will bind container's data to User model.

    • by model I mean User entity, not Vaadin's internal model

How can I do that? I have problem with 2 things:

  • creating appropriate listener
  • binding existing User model to row/index in data IndexedContainer

Explanation:

  • IndexedContainer has itemId property, where I can left user's id for future binding on update. But after creating ValueChangeListener on the IndexedContainer I found that I have no access to its itemId field.

  • So I tried with CommitHandler in EditorFieldGroup (the field of Grid object) and there is the same scenario, but I see itemId property in debug made, but I can't reach it because it is a private field. I can of course get it through reflection - but I don't think that this is a good way to do that.

Maby there is some other way to update User model from Grid tabular data?

Maby I should add User id field to grid as regular IndexedContainer property, but make it hidden and read-only? But I wonder if it is safe and there's no threat that someone change frontend form and can update User with id not presented on the Grid table.

If anyone know what is the best practice on that typical case, please let me know. I will be very glad for your help!


Solution

  • When using editable grid component you will need to use a FieldGroup. In your case you can use BeanFieldGroup. If you have right getter/setter methods the BeanFieldGroup can take care of updating your entity instance when user changes and saves data from grid. Following is a small code snippet:

    grid.setEditorFieldGroup(
        new BeanFieldGroup<Person>(User.class));
    

    Additionally you can add validations for your User entity by using standard @NotNull, @Size, @Min, @Max etc.

    For more check out book of vaadin website. Hope this helps!