Vaadin Flow Grid - how to control the columns when using JPA Entity?

474 views Asked by At

If I use JPA and Vaadin 10 Grid, it adds all the columns in an arbitrary order to the display.

grid = new Grid<>(Thing.class);
add(grid);

How do I make it add just one or two columns, and have control over the order, sizing, widths, etc.

My 'thing' looks like

@Entity
public class Thing {

   private static final Logger log = LoggerFactory.getLogger(Thing.class);

   @Id
   @GeneratedValue
   @Column(unique = true)
   private Long id;

   @Column(nullable = false, updatable = false)
   @CreationTimestamp
   private Instant creationDate;
   ...

Is there an annotation I should be using, or do I need to hide columns, or remove all the columns and add them manually? I've search online and here on SO and found nothing that seems to be related.

1

There are 1 answers

0
seraphina On

You can set the grid columns with grid.setColumns("dataField1","dataField2","dataField3") and so on. If you want to change the display name of the Field you can use grid.getColumnByKey("dataField1").setHeader("Custom Text");

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.Route;

@Route
public class MainView extends VerticalLayout {

private static final long serialVersionUID = 3461787310452366610L;
private Grid<Student> sGrid = new Grid<>(Student.class);
private TextField filter = new TextField();
private HorizontalLayout toolbar = new HorizontalLayout();
private Button newStudent = new Button("Add");
@Autowired
StudentRepository repo;

public MainView() {
    setSizeFull();
    initComponents();
    add(toolbar);
    add(sGrid);
}

private void initComponents() {
    sGrid.setColumns("firstName", "lastName", "sid", "uid");
    sGrid.getColumnByKey("sid").setHeader("Student ID");
    sGrid.getColumnByKey("uid").setHeader("Unique ID");

    toolbar.setSizeUndefined();
    toolbar.add(filter, newStudent);

    filter.setPlaceholder("Search...");

}

@PostConstruct
private void init() {
    sGrid.setItems(repo.findAll());
}

}