Search code examples
spring-bootvaadin8treegrid

Add component column only on child rows


I am developing an application on Spring boot and Vaadin 8, my question is how to generate a button only on child rows in a tree grid. I have tried this way, but buttons are generated on each row, parent and child.

private void setUpTreeGrid() {
    treeGrid = new TreeGrid<>();
    treeGrid.setSizeFull();

    treeGrid.addColumn(EmployeeDto::getEmployee).setCaption("Employee").setId("employee-column");
    treeGrid.addColumn(EmployeeDto::getComputer).setCaption("Computers").setId("computer-column");
    treeGrid.addComponentColumn(this::deleteButton).setCaption("Delete"); // Generates a button on parent and child row

    data = new TreeData<>();
    data.addItems(generateEmployee(), EmployeeDto::getSubEmployee);
    dataProvider = new TreeDataProvider<>(data);
    treeGrid.setDataProvider(dataProvider);


    addComponent(treeGrid);
}

private Button deleteButton(EmployeeDto employeeDto) {

    Button button = new Button(VaadinIcons.CLOSE);
    button.addStyleName(ValoTheme.BUTTON_SMALL);
    button.addClickListener(e -> {
     //   Delete function
        onChange();
    });
    return button;
}

This is how I set the data in tree grid

private List<EmployeeDto> generateEmployee() {
    List<Employee> employees = employeeService.findAllEmployee();

    List<EmployeeDto> employeeList = new ArrayList<>();
    for (Employee employee : employees) {
        EmployeeDto employeeDto;
        employeeDto = new EmployeeDto(employee.getUserName() + " " + employee.getFirstName() + " " + employee.getLastName(), String.valueOf(employee.getComputers().size()));
        if (!(employee.getComputers().isEmpty())) {
            employeeList.add(employeeDto);
        }
        for (int i = 0; i < employee.getComputers().size(); i++) {
            EmployeeDto subEmployee = new EmployeeDto();
            subEmployee.setComputer(employee.getComputers().get(i).getInventoryId());
            employeeDto.addSubEmployee(subEmployee);

        }
    }
    return employeeList;
}

Solution

  • Couple of thoughts for you. I recall first that there is some corner case issue to use component column as delete button, see:

    https://github.com/vaadin/framework/issues/10995

    I think this applies to TreeGrid as well.

    So one option is to use ButtonRenderer or the mentioned add on.

    Now, what is the trick to hide the button from parent rows? For this I think you need sufficent data in EmployeeDto so that it is possible to determine whether it is parent row or not.

    If yes, you can use setStyleGenerator in the column where you have the button and set in your them "display: none" with that style.