Andferdd
Andferdd

Reputation: 91

How to add converter to grid column in Vaadin 8?

I am using Vaadin 8 and I am facing a problem.

In my constructor, I create a grid which I add to a layout.

Grid<Row> grid = new Grid<>(); grid.removeAllColumns(); //Here, I add columns to the grid grid.addColumn(... grid.addColumn(… …

I then want to add a converter to my grid as follows:

 grid.getColumn("delete").setConverter(new StringToUrlConverter("dustbin"));

What I do not understand is the error message indicating why I cannot add the converter. The error message is the folloing one:

The method setConverter(StringToUrlConverter) is undefined for the type >Grid.Column<ContactView.Row,capture#1-of ?>

So how do I have to set my converter?

This is my converter:

package com.example.vaadin;

import com.vaadin.data.Converter;
import com.vaadin.data.Result;
import com.vaadin.data.ValueContext;

public class StringToUrlConverter implements Converter<String, String> {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    String imagePath = "";
    
    public StringToUrlConverter(String path) {
        this.imagePath=path;
    }

    public String getImagePath() {
        return imagePath;
    }

    @Override
    public Result<String> convertToModel(String value, ValueContext context) {
         
         return Result.ok(null);
    }

    @Override
    public String convertToPresentation(String value, ValueContext context) {
         
        if(value.equals("delete")) {
            return "<span><img src='img/" + getImagePath() + ".jpg' width='20' height='20'></span>";    
        }
        
        return "";
    }

}     


Upvotes: 3

Views: 495

Answers (1)

Tatu Lund
Tatu Lund

Reputation: 10643

There is no setConverter method in Vaadin 8, it was in Vaadin 7. Instead in Vaadin 8 and newer versions you should use version of addColumn method with value provider. See old discussion in Vaadin's Forum.

StringToUrlConverter converter = new StringToUrlConverter (path);
grid.addColumn(row -> converter.convertToPresentation(row.getDelete(), String.class, ui.getLocale())).setCaption("Delete");

But, in your case you probably do not need that either. I see from your code that you simply want to add delete button or something like that in the Grid's cell.

You can add component in Grid from Vaadin 8 onwards using:

grid.addComponentColumn(row -> {
    Image image = new Image();
    image.setSrc(path);
    image.addClickListener(event -> {
         // add code to remove the row
         grid.getDataProvider().refreshAll();
    });
    return image;
}

Upvotes: 2

Related Questions