Change cell style on edit

Hi,

I’m trying to get the cell background color to change when a value for the record is changed (manually). The table and the column is editable. It is easy to change the styling on the edit component (e.g. optionGroup) but I want the cell containing the component to change color depending on the value.

I checked the datasource listener option but could not get this refering back to the corresponding cell.

Is this even possible?

Hi,

This cannot be achieved using default editable Table, but you can implement this using custom generated columns.

First, you need to store changes map in the field of your screen controller:


protected Map<User, Set<String>> changedValues = new HashMap<>();

Next, you have to add generated column that will create a field with ValueChangeListener:


@Override
public void init(Map<String, Object> params) {
    super.init(params);

    // we will track changes of login column
    usersTable.addGeneratedColumn("login", (User entity) -> {
        TextField component = componentsFactory.createComponent(TextField.class);
        component.setWidthFull();

        component.setDatasource(usersTable.getItemDatasource(entity), "login");
        // if we change value we apply additional stylename for component
        component.addValueChangeListener(e -> {
            // add new record to changedValues
            changedValues
                    .computeIfAbsent(entity, u -> new HashSet<>())
                    .add("login");

            component.addStyleName("changed");
        });

        // if value is already changed we apply stylename as well
        if (changedValues
                .getOrDefault(entity, Collections.emptySet())
                .contains("login")) {
            component.addStyleName("changed");
        }

        return component;
    });

Finally, add to your SCSS files style definition for changed CSS class:


.changed {
  background: #90ffe6 !important;
  box-shadow: inset 0 1px 0 #90ffe6;
}

Note: Do not forget to clean this changedValues map after data commit, if you have Save/Commit button in your screen.

The result will be:

editable-table-changes

Thanks - this is a great solution.

In my case I had to change the style based on the newly selected value and while adding a ‘direct edit’ option to the table it already worked to my convenience as the table is then refreshed after each change and the style updated.

Nonetheless, this solution is great and will use it as well (but for a different purpose than what I initially was looking for).

Thanks!