Vaadin Binder getBean() is always null

Here is my code:

public class ListView extends VerticalLayout {

    Binder<UserInput> binder;

    public ListView() {
        setSpacing(false);

        binder = new Binder<>(UserInput.class);


        TextField jobTitle = new TextField();
        jobTitle.setPlaceholder("Job Title");
        jobTitle.setId("job-title");
        binder.forField(jobTitle)
                .bind(UserInput::getJobTitle, UserInput::setJobTitle);

        

        Button search = new Button("Search");
        search.setIcon(VaadinIcon.SEARCH.create());
        search.setId("search");
        search.addClickListener(buttonClickEvent -> {
            UserInput input = binder.getBean();
            System.out.println(input.getJobTitle());
        });

        
    }

}

I’m using Binder to bind the form data as shown in above code.
However, I’m getting NPE here: System.out.println(input.getJobTitle());
since input is null.

Is this expected ? What am I doing wrong here and how to fix this ?

You have to pass an instance of your bean to the binder; binder is not going to create a new instance for you.

Please, have a look at the following documentation Loading & Saving to Business Objects | Data Binding | Flow | Vaadin Docs

Sorry, I misunderstood binder as a requirement for form submissions.
But it seems like mainly for validations and conversion purposes.
All my form inputs are optional fields and used for firing a search query.
So, no validations or conversions required.

Using Binder is not mandatory, it’s a utility that’s designed to make form data binding easier. Binder doesn’t create objects for you, but you can use an existing object to supply the initial values of the form fields. Binder has two ways of operation:

  • with “unbuffered” binding, you call binder.setBean(bean) to insert an object which will update the form’s field with initial values and the object will be updated as soon as the user does anything in the UI (assuming it is valid)
  • with “buffered” binding, you don’t call setBean, but can call binder.readBean(bean) to update the UI fields from that object and binder.writeBean(bean) to update the Java object passed as parameter with values from the UI

In most cases, you don’t need to call binder.getBean() at all.

1 Like

Thank you for insights!