rmuller
rmuller

Reputation: 12859

How to use ContextMenu with Grid in Vaadin Flow?

When using Vaadin Flow (11.0.0) it should be possible to use Grid with ContextMenu (1.0.0). See issue https://github.com/vaadin/vaadin-context-menu-flow/issues/5.

This is what I have so far:

@Route("menu")
public class MenuTestView extends VerticalLayout {

    public MenuTestView() {
        final Grid<String> g = new Grid<>();
        g.setWidth("20em");
        g.addColumn(s -> s).setHeader("Word");
        g.addColumn(s -> s.length()).setHeader("Length");
        g.setItems("The quick brown fox jumps over the lazy dog".split("\\s+"));

        final Label label = new Label();

        final ContextMenu contextMenu = new ContextMenu();
        contextMenu.setTarget(g);

        contextMenu.addItem("Item 1", e -> label.setText(e.getSource().getText()));
        contextMenu.addItem("Item 2", e -> label.setText(e.getSource().getText()));

        add(g, label);
    }

}

Questions:

Upvotes: 1

Views: 2619

Answers (1)

Jens Jansson
Jens Jansson

Reputation: 4686

vaadin-grid-flow 1.2 brought specifically support to make Grid and context menu play nice together. It was released three days ago. It is possible to make them work together before, but the event didn’t tell which item the context menu was triggered on. See https://github.com/vaadin/vaadin-grid-flow/releases/tag/1.2.0

You can upgrade your grid to 1.2 by adding the following to the pom.

<dependency>
    <groupId>com.vaadin</groupId>
    <artifactId>vaadin-grid-flow</artifactId>
    <version>1.2.0</version>
</dependency>

Here’s example usage from the tests: https://github.com/vaadin/vaadin-grid-flow/blob/master/src/test/java/com/vaadin/flow/component/grid/it/ContextMenuGridPage.java

    GridContextMenu<Person> contextMenu = grid.addContextMenu();
    contextMenu.addItem("Show name of context menu target item", e -> {
        String name = e.getItem().map(Person::getName)
                .orElse("no target item");
        message.setText(name);
    });

Upvotes: 3

Related Questions