Navigating Between Views in Vaadin

So far in this tutorial series, you’ve built a CRM application for listing and editing contacts. In this chapter, you add a dashboard view to the application. You also add a responsive application layout, with a header and a navigation sidebar that can be toggled on small screens.

Application layout with a header and a sidebar

Defining View Routes

Any Vaadin component can be made a navigation target by adding an @Route("<path>") annotation. Routes can be nested by defining the parent layout in the annotation: @Route(value = "list", parent=MainLayout.class).

Creating the Parent Layout

The application should have:

  • A shared parent layout with two child views:

    MainLayout: App Layout with header and navigation:

    1. ListView: The default view, mapped to "".

    2. DashboardView: Mapped to "dashboard".

  • A responsive app layout and navigation links.

Begin by creating a new Java class named MainLayout in the views package with the following content. This is the shared parent layout of both views in the application.

MainLayout.java

  1. package com.example.application.views;
  2. import com.example.application.views.list.ListView;
  3. import com.vaadin.flow.component.applayout.AppLayout;
  4. import com.vaadin.flow.component.applayout.DrawerToggle;
  5. import com.vaadin.flow.component.html.H1;
  6. import com.vaadin.flow.component.orderedlayout.FlexComponent;
  7. import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
  8. import com.vaadin.flow.component.orderedlayout.VerticalLayout;
  9. import com.vaadin.flow.router.HighlightConditions;
  10. import com.vaadin.flow.router.RouterLink;
  11. import com.vaadin.flow.server.PWA;
  12. import com.vaadin.flow.theme.Theme;
  13. @Theme(themeFolder = "flowcrmtutorial") 1
  14. public class MainLayout extends AppLayout { 2
  15. public MainLayout() {
  16. createHeader();
  17. createDrawer();
  18. }
  19. private void createHeader() {
  20. H1 logo = new H1("Vaadin CRM");
  21. logo.addClassNames("text-l", "m-m");
  22. HorizontalLayout header = new HorizontalLayout(
  23. new DrawerToggle(), 3
  24. logo
  25. );
  26. header.setDefaultVerticalComponentAlignment(FlexComponent.Alignment.CENTER); 4
  27. header.setWidth("100%");
  28. header.addClassNames("py-0", "px-m");
  29. addToNavbar(header); 5
  30. }
  31. private void createDrawer() {
  32. RouterLink listLink = new RouterLink("List", ListView.class); 6
  33. listLink.setHighlightCondition(HighlightConditions.sameLocation()); 7
  34. addToDrawer(new VerticalLayout( 8
  35. listLink
  36. ));
  37. }
  38. }
  1. Move the @Theme annotation to MainLayout.

  2. AppLayout is a Vaadin layout with a header and a responsive drawer.

  3. DrawerToggle is a menu button that toggles the visibility of the sidebar.

  4. Centers the components in the header along the vertical axis.

  5. Adds the header layout to the application layout’s nav bar, the section at the top of the screen.

  6. Creates a RouterLink with the text “List” and ListView.class as the destination view.

  7. Sets setHighlightCondition(HighlightConditions.sameLocation()) to avoid highlighting the link for partial route matches. (Technically, every route starts with an empty route, so without this it would always show up as active, even though the user is not on the view.)

  8. Wraps the link in a VerticalLayout and adds it to the `AppLayout’s drawer.

Add the following CSS to frontend/themes/flowcrmtutorial/styles.css to highlight the selected link.

styles.css

  1. a[highlight] {
  2. font-weight: bold;
  3. text-decoration: underline;
  4. }

Lastly, in ListView update the @Route mapping to use the new MainLayout and delete the @Theme annotation.

ListView.java

  1. @Route(value="", layout = MainLayout.class) 1
  2. 2
  3. @PageTitle("Contacts | Vaadin CRM")
  4. public class ListView extends VerticalLayout {
  5. ...
  6. }
  1. ListView still matches the empty path, but now uses MainLayout as its parent.

  2. The @Theme annotation is now removed, as it is now on MainLayout instead.

Run the application. You should now see a header and a sidebar on the list view.

Application with sidebar list view

Creating a Dashboard View

Next, create a new dashboard view. This view shows stats: the number of contacts in the system and a pie chart of the number of contacts per company.

Dashboard view

Create a new Java class named DashboardView in the views package with the following content:

DashboardView.java

  1. package com.example.application.views;
  2. import com.example.application.data.service.CrmService;
  3. import com.vaadin.flow.component.Component;
  4. import com.vaadin.flow.component.charts.Chart;
  5. import com.vaadin.flow.component.charts.model.ChartType;
  6. import com.vaadin.flow.component.charts.model.DataSeries;
  7. import com.vaadin.flow.component.charts.model.DataSeriesItem;
  8. import com.vaadin.flow.component.html.Span;
  9. import com.vaadin.flow.component.orderedlayout.VerticalLayout;
  10. import com.vaadin.flow.router.PageTitle;
  11. import com.vaadin.flow.router.Route;
  12. @Route(value = "dashboard", layout = MainLayout.class) 1
  13. @PageTitle("Dashboard | Vaadin CRM")
  14. public class DashboardView extends VerticalLayout {
  15. private final CrmService service;
  16. public DashboardView(CrmService service) { 2
  17. this.service = service;
  18. addClassName("dashboard-view");
  19. setDefaultHorizontalComponentAlignment(Alignment.CENTER); 3
  20. add(getContactStats(), getCompaniesChart());
  21. }
  22. private Component getContactStats() {
  23. Span stats = new Span(service.countContacts() + " contacts"); 4
  24. stats.addClassNames("text-xl", "mt-m");
  25. return stats;
  26. }
  27. private Chart getCompaniesChart() {
  28. Chart chart = new Chart(ChartType.PIE);
  29. DataSeries dataSeries = new DataSeries();
  30. service.findAllCompanies().forEach(company ->
  31. dataSeries.add(new DataSeriesItem(company.getName(), company.getEmployeeCount()))); 5
  32. chart.getConfiguration().setSeries(dataSeries);
  33. return chart;
  34. }
  35. }
  1. DashboardView is mapped to the "dashboard" path and uses MainLayout as a parent layout.

  2. Takes CrmService as a constructor parameter and saves it as a field.

  3. Centers the contents of the layout.

  4. Calls the service to get the number of contacts.

  5. Calls the service to get all companies, then creates a DataSeriesItem for each, containing the company name and employee count.

Note
Vaadin Charts is a Commercial Component Set

Vaadin Charts is a collection of data visualization components that is a part of the Vaadin Pro subscription. Vaadin Charts comes with a free trial that you can activate in the browser. All Vaadin Pro tools and components are free for students through the GitHub Student Developer Pack.

Open Company.java and add the following field and getter to get the employee count without having to fetch all the entities.

Company.java

  1. @Formula("(select count(c.id) from Contact c where c.company_id = id)") 1
  2. private int employeeCount;
  3. public int getEmployeeCount(){
  4. return employeeCount;
  5. }
  1. The Formula will get the count of employees without needing to fetch all the employees.

Add the Dashboard View to the Main Layout Sidebar

Add a navigation link to DashboardView in the MainLayout drawer:

MainLayout.java

  1. private void createDrawer() {
  2. RouterLink listLink = new RouterLink("List", ListView.class);
  3. listLink.setHighlightCondition(HighlightConditions.sameLocation());
  4. addToDrawer(new VerticalLayout(
  5. listLink,
  6. new RouterLink("Dashboard", DashboardView.class)
  7. ));
  8. }

Build and run the application. You should now be able to navigate to the dashboard view and see stats on your CRM contacts. If you want to, go ahead and add or remove contacts in the list view to see that the dashboard reflects your changes.

Complete dashboard view

In the next chapter, you’ll secure the application by adding a login screen.

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