Vaadin flow: grid conditional background color

2019-08-17 02:52发布

问题:

I want to color grid lines, depending on a condition. I try this:

Java:

gridEtudiant.setClassNameGenerator(t -> {
    if (t.getEtud_numero().startsWith("2")) {
        return "error_row";
    }
    return "";
});

Css:

td.error_row {
  background-color: red;
}

HTML

<td id="vaadin-grid-cell-1" tabindex="0" role="gridcell" part="cell body-cell" first-column="" reorder-status="undefined" aria-selected="false" class="error_row" style="width: 100px; flex-grow: 1; order: 10000000;"><slot name="vaadin-grid-cell-content-1"></slot></td>

We can see the 'class="error_row"' but it's not colored in red.

Vaadin version is 13.0.1

回答1:

Your java code looks good.

Make sure you have a html file like webapp/frontend/styles/shared-styles.html containing something like:

<dom-module id="my-grid-theme" theme-for="vaadin-grid">
    <template>
        <style>
            [part~="cell"].error_row {
                background: red;
            }
        </style>
    </template>
</dom-module>

If you then have your Layout containing the grid annotated with @HtmlImport("frontend://styles/shared-styles.html") (which you already seem to have as your custom css class is already applied) it should work.

Example:

grid.addColumn(Customer::getFirstname).setHeader("Firstname");
grid.addColumn(Customer::getLastname).setHeader("Lastname");
grid.addColumn(Customer::getEmail).setHeader("Email");
grid.setClassNameGenerator(customer -> {
    if (customer.getFirstname().equals("Marco")) {
       return "error_row";
    } else {
       return "";
    }
});

becomes: