Vaadin Refer to mainLayout from RouterLayout

Viewed 222

I need to create a buffer between the application screens. I think to make a buffer in the mainLayout but I can't access it from the child layers

I tried to do it through 'static', then the buffer is common for all users, and this is incorrect

Cookies are also unsuitable because the data structure is complex

Code with static buffer:

in the example, a table is created, when you select elements in the table, they are written to the buffer, and if there are elements in the buffer, they are marked in the table

MainLayout.java

public class MainLayout extends AppLayout implements RouterLayout {


    public static Set<Test> buffer;

    public MainLayout() {
        buffer = new HashSet<Test>();
        /*...*/
    }
}

BasicView.java

@Route(value = "BasicView", layout = MainLayout.class)
@RouteAlias(value = "/BasicView", layout = MainLayout.class)
public class BasicView extends VerticalLayout {

    private final Grid<Test> tests;

    public BasicView(@Autowired TestService){
        /*...*/
        tests = new Grid<>(Test.class, false);
        tests.addSelectionListener(event -> {
        MainLayout.buffer = event.getAllSelectedItems();});
        /*...*/
        for(Test el : MainLayout.buffer)
        {
           tests.select(el);
        }
        /*...*/
    }
}
1 Answers

You can actually traverse parents of the layout upto main layout. E.g. you can do something lie below

    Optional<Component> parent = this.getParent();
    Buffer buffer = null;
    while (parent.isPresent()) {
        Component p = parent.get();
        if (p instanceof MainLayout) {
            MainLayout main = (MainLayout) p;
            buffer = main.getBuffer();
        }
        parent = p.getParent();
    }

However I am not sure if it is the best approach. If you happen to use e.g. Spring Boot, it would be more natural to have this buffer as VaadinSessionScoped bean, and Autowire it where needed. The next version of Vaadin will also add specific RouteScope, which allows more pin-point scoping if needed.

See also old Vaadin Forum discussion about this: https://vaadin.com/forum/thread/17917385/vaadin-14-accessing-components-of-mainview

Related