How to color a row or cell of a grid depending on it's data in Vaadin 14
Asked Answered
B

1

3

Suppose I have a Grid<Person> and some person.getStatus() which returns an Enum

enum Status {
SINGLE, MARRIED, DIVORCED
}

I'd like to color the grid's column according to this enum's value.

How can it be done?

Breakfast answered 29/2, 2020 at 11:4 Comment(6)
What Vaadin version are you using?Rake
latest (14.1.17), @RalfWagnerBreakfast
Oh, is it with setClassNameGenerator?Breakfast
I assume you want to color the cell not the column?Korea
I want to color the whole rowBreakfast
Actually, if it's a huge problem, I wouldn't mind coloring only the column itselfBreakfast
R
12

In Vaadin 14

Style a Grid row based on data

First, you need to set the CSS class name generator for the row. This will add the CSS class name to the td elements created by Grid. The generator function receives your item and you should return a CSS class name as a String or null if you don't want to add a class name for certain rows. Multiple class names can be returned from the generator as space-separated.

grid.setClassNameGenerator(person -> {
    if (person.getStatus() == Status.DIVORCED || person.getStatus() == Status.SINGLE) {
        return "my-style-1";
    } else {
        return "my-style-2";
    }
});

To change the style based on the CSS class names, you need to create a theme for Grid.

In frontend/styles folder add styles.css.

td.my-style-1 {
    background-color: black;
    color: hotpink;
}

td.my-style-2 {
    background-color: hotpink;
    color: black;
}

And include the style to your app.

@Route
@CssImport(value = "./styles/styles.css", themeFor = "vaadin-grid")
public class MainView extends VerticalLayout {
// your code for grid
}

Style a Grid cell based on data

The CSS style importing and creating is done the same way as with row styling, but the Grid API used is different.

For a cell, you should use the column class name generator:

grid.getColumnByKey("status").setClassNameGenerator(person -> {
    if (person.getStatus() == Status.SINGLE) {
        return "my-style-3";
    }
    return null;
});
Roberto answered 29/2, 2020 at 12:8 Comment(1)
Your color choices in your example code live up to your name.Warrenwarrener

© 2022 - 2024 — McMap. All rights reserved.