Passing Data and Events Between Vaadin Components

In the previous chapter, you created a reusable form component to edit contacts. In this chapter, you hook it up to the rest of the view and manage the view state.

The form:

  • Shows the selected contact in the grid.

  • Is hidden when no contact is selected.

  • Saves and deletes contacts in the database.

Showing the Selected Contact in the Form

The first step is to show the selected grid row in the form.

To do this, update ListView as follows:

ListView.java

  1. package com.example.application.views.list;
  2. import com.example.application.data.entity.Contact;
  3. import com.example.application.data.service.CrmService;
  4. import com.vaadin.flow.component.button.Button;
  5. import com.vaadin.flow.component.grid.Grid;
  6. import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
  7. import com.vaadin.flow.component.orderedlayout.VerticalLayout;
  8. import com.vaadin.flow.component.textfield.TextField;
  9. import com.vaadin.flow.data.value.ValueChangeMode;
  10. import com.vaadin.flow.router.PageTitle;
  11. import com.vaadin.flow.router.Route;
  12. import com.vaadin.flow.theme.Theme;
  13. @Route(value = "")
  14. @Theme(themeFolder = "flowcrmtutorial")
  15. @PageTitle("Contacts | Vaadin CRM")
  16. public class ListView extends VerticalLayout {
  17. Grid<Contact> grid = new Grid<>(Contact.class);
  18. TextField filterText = new TextField();
  19. ContactForm form;
  20. CrmService service;
  21. public ListView(CrmService service) {
  22. this.service = service;
  23. addClassName("list-view");
  24. setSizeFull();
  25. configureGrid();
  26. configureForm();
  27. add(getToolbar(), getContent());
  28. updateList();
  29. closeEditor(); 1
  30. }
  31. private HorizontalLayout getContent() {
  32. HorizontalLayout content = new HorizontalLayout(grid, form);
  33. content.setFlexGrow(2, grid);
  34. content.setFlexGrow(1, form);
  35. content.addClassNames("content");
  36. content.setSizeFull();
  37. return content;
  38. }
  39. private void configureForm() {
  40. form = new ContactForm(service.findAllCompanies(), service.findAllStatuses());
  41. form.setWidth("25em");
  42. }
  43. private void configureGrid() {
  44. grid.addClassNames("contact-grid");
  45. grid.setSizeFull();
  46. grid.setColumns("firstName", "lastName", "email");
  47. grid.addColumn(contact -> contact.getStatus().getName()).setHeader("Status");
  48. grid.addColumn(contact -> contact.getCompany().getName()).setHeader("Company");
  49. grid.getColumns().forEach(col -> col.setAutoWidth(true));
  50. grid.asSingleSelect().addValueChangeListener(event ->
  51. editContact(event.getValue())); 2
  52. }
  53. private HorizontalLayout getToolbar() {
  54. filterText.setPlaceholder("Filter by name...");
  55. filterText.setClearButtonVisible(true);
  56. filterText.setValueChangeMode(ValueChangeMode.LAZY);
  57. filterText.addValueChangeListener(e -> updateList());
  58. Button addContactButton = new Button("Add contact");
  59. addContactButton.addClickListener(click -> addContact()); 3
  60. HorizontalLayout toolbar = new HorizontalLayout(filterText, addContactButton);
  61. toolbar.addClassName("toolbar");
  62. return toolbar;
  63. }
  64. public void editContact(Contact contact) { 4
  65. if (contact == null) {
  66. closeEditor();
  67. } else {
  68. form.setContact(contact);
  69. form.setVisible(true);
  70. addClassName("editing");
  71. }
  72. }
  73. private void closeEditor() {
  74. form.setContact(null);
  75. form.setVisible(false);
  76. removeClassName("editing");
  77. }
  78. private void addContact() { 5
  79. grid.asSingleSelect().clear();
  80. editContact(new Contact());
  81. }
  82. private void updateList() {
  83. grid.setItems(service.findAllContacts(filterText.getValue()));
  84. }
  85. }
  1. The closeEditor() call at the end of the constructor

    • sets the form contact to null, clearing out old values,

    • hides the form,

    • removes the "editing" CSS class from the view.

  2. addValueChangeListener() adds a listener to the grid. The Grid component supports multi- and single-selection modes. You only need to select a single Contact, so you can use the asSingleSelect() method. The getValue() method returns the Contact in the selected row, or null if there’s no selection.

  3. Call addContact() when the user clicks on the “Add contact” button.

  4. editContact() sets the selected contact in the ContactForm and hides or shows the form, depending on the selection. It also sets the "editing" CSS class name when editing.

  5. addContact() clears the grid selection and creates a new Contact.

Build the application. You should now be able to select contacts in the grid and see them in the form. But, none of the buttons work yet.

form showing a contact

Making the Layout Responsive

To make the layout responsive and usable on both mobile and desktop, we need to add CSS.

To do this, add the following CSS to frontend/themes/flowcrmtutorial/styles.css:

styles.css

  1. @media all and (max-width: 1100px) {
  2. .list-view.editing .toolbar,
  3. .list-view.editing .contact-grid {
  4. display: none;
  5. }
  6. }

The CSS media query will hide the grid and the toolbar when you are editing contacts on a narrow screen.

Handling Form Events

The ContactForm API is designed to be reusable; it is configurable through properties and it fires the necessary events. So far, you have passed a list of companies, statuses, and the contact to the form. Now, all you need to do is listen for the events to complete the integration.

To handle event listeners, update configureForm() and add saveContact() and deleteContact() methods.

ListView.java

  1. private void configureForm() {
  2. form = new ContactForm(service.findAllCompanies(), service.findAllStatuses());
  3. form.setWidth("25em");
  4. form.addListener(ContactForm.SaveEvent.class, this::saveContact); 1
  5. form.addListener(ContactForm.DeleteEvent.class, this::deleteContact); 2
  6. form.addListener(ContactForm.CloseEvent.class, e -> closeEditor()); 3
  7. }
  8. private void saveContact(ContactForm.SaveEvent event) {
  9. service.saveContact(event.getContact());
  10. updateList();
  11. closeEditor();
  12. }
  13. private void deleteContact(ContactForm.DeleteEvent event) {
  14. service.deleteContact(event.getContact());
  15. updateList();
  16. closeEditor();
  17. }
  1. The save event listener calls saveContact(). It:

    1. uses contactService to save the contact in the event to the database,

    2. updates the list,

    3. closes the editor.

  2. The delete event listener calls deleteContact(). It:

    1. uses contactService to delete the contact from the database,

    2. updates the list,

    3. closes the editor.

  3. The close event listener closes the editor.

Build the application and verify that you are now able to select, add, update, and delete contacts.

The selected contact has updated first and last names.

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. }