Creating a Form Component for Editing Contacts

The list view now has a grid to display Contact objects. To complete the view, you need to create a form for editing contacts.

A screenshot of the application highlighting the contact editing form

This chapter covers:

  • Creating a new component.

  • Importing and using a custom component.

Creating Components Using Composition

Vaadin Flow is a component-based framework. You’ve already worked with several components, like Grid, TextField, and VerticalLayout. But, the real power of the component-based architecture is in the ability to create your own components.

Instead of building an entire view in a single class, your view can be composed of smaller components that each handle different parts of the view. The advantage of this approach is that individual components are easier to understand and test. The top-level view is used mainly to orchestrate the components.

Creating a Form Component

The form component you will create has:

  • Text fields for the first and last name.

  • An email field.

  • Two select fields: one to select the company and the other to select the contact status.

Create a new file, ContactForm.java, in the com.example.application.views.list package. If you are using IntelliJ, copy the code below and paste it into the views package. IntelliJ will automatically create the file.

Create a file automatically by pasting a class definition onto a Java package in IntelliJ IDEA.

ContactForm.java

  1. package com.example.application.views.list;
  2. import com.example.application.data.entity.Company;
  3. import com.example.application.data.entity.Status;
  4. import com.vaadin.flow.component.Key;
  5. import com.vaadin.flow.component.button.Button;
  6. import com.vaadin.flow.component.button.ButtonVariant;
  7. import com.vaadin.flow.component.combobox.ComboBox;
  8. import com.vaadin.flow.component.formlayout.FormLayout;
  9. import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
  10. import com.vaadin.flow.component.textfield.EmailField;
  11. import com.vaadin.flow.component.textfield.TextField;
  12. import java.util.List;
  13. public class ContactForm extends FormLayout { 1
  14. TextField firstName = new TextField("First name"); 2
  15. TextField lastName = new TextField("Last name");
  16. EmailField email = new EmailField("Email");
  17. ComboBox<Status> status = new ComboBox<>("Status");
  18. ComboBox<Company> company = new ComboBox<>("Company");
  19. Button save = new Button("Save");
  20. Button delete = new Button("Delete");
  21. Button close = new Button("Cancel");
  22. public ContactForm(List<Company> companies, List<Status> statuses) {
  23. addClassName("contact-form"); 3
  24. company.setItems(companies);
  25. company.setItemLabelGenerator(Company::getName);
  26. status.setItems(statuses);
  27. status.setItemLabelGenerator(Status::getName);
  28. add(firstName, 4
  29. lastName,
  30. email,
  31. company,
  32. status,
  33. createButtonsLayout());
  34. }
  35. private HorizontalLayout createButtonsLayout() {
  36. save.addThemeVariants(ButtonVariant.LUMO_PRIMARY); 5
  37. delete.addThemeVariants(ButtonVariant.LUMO_ERROR);
  38. close.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
  39. save.addClickShortcut(Key.ENTER); 6
  40. close.addClickShortcut(Key.ESCAPE);
  41. return new HorizontalLayout(save, delete, close); 7
  42. }
  43. }
  1. ContactForm extends FormLayout, a responsive layout that shows form fields in 1 or 2 columns depending on viewport width.

  2. Creates all the UI components as fields in the component.

  3. Gives the component a CSS class name, so you can style it later.

  4. Adds all the UI components to the layout.

    The buttons require a bit of extra configuration. Create and call a new method, createButtonsLayout().

  5. Makes the buttons visually distinct from each other using built-in theme variants.

  6. Defines keyboard shortcuts: Enter to save and Escape to close the editor.

  7. Returns a HorizontalLayout containing the buttons to place them next to each other.

Adding the Form to the Main View

The next step is to add the form to the main view.

To do this, amend ListView as follows:

ListView.java

  1. public class ListView extends VerticalLayout {
  2. Grid<Contact> grid = new Grid<>(Contact.class);
  3. TextField filterText = new TextField();
  4. ContactForm form; 1
  5. public ListView() {
  6. addClassName("list-view");
  7. setSizeFull();
  8. configureGrid();
  9. configureForm(); 2
  10. add(getToolbar(), getContent()); 3
  11. }
  12. private Component getContent() {
  13. HorizontalLayout content = new HorizontalLayout(grid, form);
  14. content.setFlexGrow(2, grid); 4
  15. content.setFlexGrow(1, form);
  16. content.addClassNames("content");
  17. content.setSizeFull();
  18. return content;
  19. }
  20. private void configureForm() {
  21. form = new ContactForm(Collections.emptyList(), Collections.emptyList()); 5
  22. form.setWidth("25em");
  23. }
  24. // Remaining methods omitted
  25. }
  1. Creates a field for the form, so you have access to it from other methods later on.

  2. Create a method for initializing the form.

  3. Change the add() method to call getContent(). The method returns a HorizontalLayout that wraps the form and the grid, showing them next to each other.

  4. Use setFlexGrow() to define that the Grid should get two times the space of the form.

  5. Initialize the form with empty company and status lists for now; you add these in the next chapter.

Build the project to reload the browser. You should now see the form on the right side of the grid.

The form component is visible to the right of the grid.

Now that you have the view built, it is time to connect it to the backend.

migration assistance

Download free e-book.
The complete guide is also available in an easy-to-follow PDF format.

https://pages.vaadin.com/en/build-a-modern-web-app-with-spring-boot-vaadin-pdf

Open in anew tab

Show code

render-banner.ts

  1. export class RenderBanner extends HTMLElement {
  2. connectedCallback() {
  3. this.renderBanner();
  4. }
  5. renderBanner() {
  6. let bannerWrapper = document.getElementById('tocBanner');
  7. if (bannerWrapper) {
  8. return;
  9. }
  10. let tocEl = document.getElementById('toc');
  11. // Add an empty ToC div in case page doesn't have one.
  12. if (!tocEl) {
  13. const pageTitle = document.querySelector(
  14. 'main > article > header[class^=PageHeader-module--pageHeader]'
  15. );
  16. tocEl = document.createElement('div');
  17. tocEl.classList.add('toc');
  18. pageTitle?.insertAdjacentElement('afterend', tocEl);
  19. }
  20. // Prepare banner container
  21. bannerWrapper = document.createElement('div');
  22. bannerWrapper.id = 'tocBanner';
  23. tocEl?.appendChild(bannerWrapper);
  24. // Banner elements
  25. const text = document.querySelector('.toc-banner-source-text')?.innerHTML;
  26. const link = document.querySelector('.toc-banner-source-link')?.textContent;
  27. const bannerHtml = `<div class='toc-banner'>
  28. <a href='${link}'>
  29. <div class="toc-banner--img"></div>
  30. <div class='toc-banner--content'>${text}</div>
  31. </a>
  32. </div>`;
  33. bannerWrapper.innerHTML = bannerHtml;
  34. // Add banner image
  35. const imgSource = document.querySelector('.toc-banner-source .image');
  36. const imgTarget = bannerWrapper.querySelector('.toc-banner--img');
  37. if (imgSource && imgTarget) {
  38. imgTarget.appendChild(imgSource);
  39. }
  40. }
  41. }