Vaadin: Highlight empty components with error message on submitting

127 views Asked by At

I have a question on how does the vaadin framework work with setRequired(true). What I found is when user focuses the component field and then exiting it, the error message appears. Here are the fields that are in my Dialog.

    private final TextField nameField = new TextField("Expense Name");
    private final TextArea descriptionField = new TextArea("Description");
    private final NumberField amountField = new NumberField("Amount");
    private final ComboBox<String> intervalField = new ComboBox<>("Interval");
    private final ComboBox<String> categoryField = new ComboBox<>("Category");
    private final DatePicker dateField = new DatePicker("Date");

    private final Component[] requiredComponents = {nameField, amountField, categoryField, intervalField};

    //...

    private List<Component> getListOfEmptyComponents() {
        return Arrays.stream(requiredComponents)
                .filter(component -> component instanceof HasValue<?, ?> && ((HasValue<?, ?>) component).isEmpty())
                .collect(Collectors.toList());
    }

    private void setupRequiredComponents() {
        Arrays.stream(requiredComponents).forEach(c -> {
            ((HasValue<?, ?>) c).setRequiredIndicatorVisible(true);
            ((HasValidationProperties) c).setErrorMessage("Please fill this field");
        });
    }

I want, after the user presses the "Save" button, all the empty required fields to be like the screenshot below.

enter image description here

These error messages are gain after I click (focus) the field and left it, and the components have the setRequiredIndicatorVisible(true);, but I want them to be visible after user clicks on Save button. Is this possible without me adding my own error messages and styling them ? Any help will be great!

1

There are 1 answers

2
Knoobie On

Instead of manually adding required and other validations to your fields, it's recommended to use the Binder.

https://vaadin.com/docs/latest/binding-data/components-binder

Once the user pressed save and you check whether or not the form is valid. The validate method of the binder also displays all fields as invalid, like shown in your requirement once you let it validate the form on save.