> Markdown version of [Add Data](https://vaadin.com/docs/latest/fr/getting-started/tutorial/add-data). Section index: [llms.txt](https://vaadin.com/docs/latest/fr/getting-started/llms.txt)

# Ajouter des produits

Dans les étapes précédentes, vous avez créé un tiroir pour modifier les détails de l’élément actuellement sélectionné dans le catalogue de produits. Cependant, il n’y avait aucun moyen d’ajouter de nouveaux éléments. Vous allez corriger cela dans cette étape. Toutefois, au lieu d’utiliser à nouveau le tiroir, vous allez créer un dialog.

> **Tip: Dialog ou Drawer?**
>
> La modification d’un élément est intrinsèquement contextuelle ; elle n’a de sens que lorsqu’il *y a* un élément sélectionné. Pour cette raison, le drawer est explicitement lié à la sélection dans l’UI.
>
> La création d’un nouvel élément n’est *pas* liée à une sélection existante. Un dialog communique clairement cette distinction : il représente une nouvelle interaction temporaire qui est indépendante de l’état actuel de la vue. En séparant la création dans un dialog, l’UI rend évident que l’utilisateur ne modifie pas quelque chose qui existe déjà, mais définit quelque chose de nouveau.

Vous commencerez par créer le dialog et ajouter un bouton pour l’ouvrir dans la vue du catalogue de produits. Vous ajouterez ensuite la logique nécessaire pour insérer de nouveaux produits dans la base de données, rafraîchir le grid, et gérer les erreurs éventuelles. Enfin, vous apporterez quelques améliorations à l’expérience utilisateur.

## <a id="créer-un-dialog-dajout-de-produit"></a>Créer un dialog d’ajout de produit

Vous allez maintenant créer un [Dialog](https://vaadin.com/docs/latest/fr/components/dialog.md) pour ajouter de nouveaux produits au catalogue. Un dialog dans Vaadin étend la classe `Dialog`. Il possède un en-tête, un pied de page, et une zone de contenu, et il peut être ouvert et fermé.

Vous réutiliserez le `ProductForm` des étapes précédentes et l’afficherez dans la zone de contenu. Vous ajouterez deux boutons au pied de page : un bouton **Save** pour insérer le nouveau produit, et un bouton **Cancel** pour fermer le dialog sans enregistrer.

Créez une nouvelle classe `AddProductDialog` comme ceci :

AddProductDialog.java

```java
package com.example.product;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.dialog.Dialog;

class AddProductDialog extends Dialog {

    private final ProductForm form;

    AddProductDialog() {
        // Create components
        form = new ProductForm();
        var saveButton = new Button("Save");
        saveButton.addThemeVariants(ButtonVariant.PRIMARY);
        var cancelButton = new Button("Cancel");

        // Layout dialog
        setHeaderTitle("Add Product"); // (1)
        add(form); // (2)
        getFooter().add(cancelButton, saveButton); // (3)
    }
}
```

1. L’en-tête contient un titre.

2. La zone de contenu contient le formulaire produit lui-même.

3. Le pied de page contient les boutons Cancel et Save.

Chaque fois que vous construisez un élément d’interface utilisateur dans Vaadin, vous voulez voir à quoi il ressemble le plus rapidement possible. Pour voir à quoi ressemble `AddProductDialog`, vous devez l’ouvrir quelque part dans votre application. Vous allez faire cela ensuite.

## <a id="afficher-le-dialog"></a>Afficher le dialog

Pour ajouter un nouveau produit, l’utilisateur doit cliquer sur un bouton **Add Product** dans la vue du catalogue de produits. Le bouton doit apparaître sur la même ligne que le champ de recherche, mais dans le coin supérieur droit de l’écran. Pour implémenter cela, vous devez faire deux choses :

1. Créer un nouveau `Button` qui ouvre `AddProductDialog` au clic.

2. Déplacer le champ de recherche dans une nouvelle barre d’outils, et y ajouter également le bouton.

Modifiez le code de `ProductCatalogView` comme suit :

ProductCatalogView\.java

```java
package com.example.product;

// tag::snippet[]
import com.vaadin.flow.component.button.Button;
// end::snippet[]
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.masterdetaillayout.MasterDetailLayout;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import org.springframework.dao.OptimisticLockingFailureException;

@Route("")
@PageTitle("Product Catalog")
class ProductCatalogView extends MasterDetailLayout {

    ProductCatalogView(ProductCatalogService service) {
        // Create components
        var searchField = new SearchField();

        var grid = new ProductCatalogGrid();
        grid.setItemsPageable(pageable -> service
            .findItems(searchField.getValue(), pageable)
        ).setIdentifierProvider(ProductCatalogItem::productId);

        var drawer = new ProductFormDrawer(productDetails -> {
            var saved = service.save(productDetails);
            grid.getDataProvider().refreshAll();
            return saved;
        }, productDetails -> {
            service.delete(productDetails);
            grid.deselectAll();
            grid.getDataProvider().refreshAll();
        }, this::handleException);

        searchField.addValueChangeListener(e ->
                grid.getDataProvider().refreshAll());

        grid.addSelectionListener(e -> {
            var productDetails = e.getFirstSelectedItem()
                .flatMap(item -> service.findDetailsById(item.productId()));
            productDetails.ifPresent(drawer::setProductDetails);
            setDetail(productDetails.isPresent() ? drawer : null);
        });
        addBackdropClickListener(e -> grid.deselectAll());
        addDetailEscapePressListener(e -> grid.deselectAll());

// tag::snippet[]
        var addButton = new Button("Add Product",
            e -> new AddProductDialog().open()); // (1)
// end::snippet[]

        // Layout view
        setSizeFull();
        setDetailSize("300px");
        setExpandMaster(true);

// tag::snippet[]
        var toolbar = new HorizontalLayout(); // (2)
        toolbar.setWidthFull(); // (3)
        toolbar.addToStart(searchField); // (4)
        toolbar.addToEnd(addButton); // (5)

        var listLayout = new VerticalLayout(toolbar, grid);
// end::snippet[]
        listLayout.setSizeFull();
        grid.setSizeFull();

        setMaster(listLayout);
    }

    private void handleException(RuntimeException exception) {
        if (exception instanceof OptimisticLockingFailureException) {
            new WarningNotification("Another user has edited the same product. "
                + "Please refresh and try again.").open();
        } else {
            // Delegate to Vaadin's default error handler
            throw exception;
        }
    }

    static class SearchField extends TextField {

        SearchField() {
            setPlaceholder("Search");
            setPrefixComponent(VaadinIcon.SEARCH.create());
            setValueChangeMode(ValueChangeMode.LAZY);
        }
    }

    static class WarningNotification extends Notification {

        WarningNotification(String text) {
            super(text, 3000, Position.MIDDLE);
            addThemeVariants(NotificationVariant.WARNING);
        }
    }
}
```

1. Ouvrez le dialog en appelant la méthode `open()`.

2. La barre d’outils est un layout horizontal.

3. Faites en sorte que la barre d’outils occupe toute la largeur de la vue. Par défaut, elle ne s’étend que pour s’adapter aux composants qu’elle contient.

4. Ajoutez le champ de recherche au début de la barre d’outils, afin qu’il apparaisse dans le coin supérieur gauche de l’écran.

5. Ajoutez le bouton à la fin de la barre d’outils, afin qu’il apparaisse dans le coin supérieur droit de l’écran.

La vue du catalogue de produits devrait maintenant ressembler à ceci :

[Image: The product catalog view with an Add Product button in the top-right corner]

Cliquez sur le bouton pour ouvrir le dialog. Il devrait ressembler à ceci :

[Image: The Add Product dialog]

Vous remarquerez que le formulaire a un aspect différent de celui du drawer. Cela s’explique par le fait que le composant [Form Layout](https://vaadin.com/docs/latest/fr/components/form-layout.md) est responsive par défaut et détermine automatiquement le nombre de colonnes en fonction de divers paramètres, tels que l’espace horizontal disponible.

Fermez le dialog en appuyant sur `Esc` ou en cliquant en dehors du dialog. Vous ajouterez ensuite la fonctionnalité aux boutons du dialog.

## <a id="implémenter-les-boutons-du-dialog"></a>Implémenter les boutons du dialog

Le bouton **Cancel** est trivial à implémenter : il doit fermer le dialog au clic. Vous faites cela en appelant la méthode `close()` dans le listener de clic du bouton.

Le bouton **Save** est plus intéressant : il doit valider le formulaire, insérer le produit dans le catalogue, rafraîchir le grid, et fermer le dialog. Vous utiliserez le même pattern de conception basé sur des callbacks que celui utilisé dans `ProductFormDrawer`. Cela maintient un style de code cohérent et vous permet aussi de réutiliser une partie de la logique de `ProductCatalogView`.

Mettez à jour `AddProductDialog` comme suit :

AddProductDialog.java

```java
package com.example.product;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.dialog.Dialog;

class AddProductDialog extends Dialog {

// tag::snippet[]
    @FunctionalInterface
    interface SaveCallback {
        void save(ProductDetails productDetails); // (1)
    }

    @FunctionalInterface
    interface ErrorCallback {
        void handleException(RuntimeException e);
    }
    private final SaveCallback saveCallback;
    private final ErrorCallback errorCallback;
// end::snippet[]
    private final ProductForm form;

// tag::snippet[]
    AddProductDialog(SaveCallback saveCallback, ErrorCallback errorCallback) {
        this.saveCallback = saveCallback;
        this.errorCallback = errorCallback;
// end::snippet[]

        // Create components
        form = new ProductForm();
// tag::snippet[]
        form.setFormDataObject(new ProductDetails()); // (2)
        var saveButton = new Button("Save", e -> save());
// end::snippet[]
        saveButton.addThemeVariants(ButtonVariant.PRIMARY);
// tag::snippet[]
        var cancelButton = new Button("Cancel", e -> close());
// end::snippet[]

        // Layout dialog
        setHeaderTitle("Add Product");
        add(form);
        getFooter().add(cancelButton, saveButton);
    }

// tag::snippet[]
    private void save() { // (3)
        form.getFormDataObject().ifPresent(productDetails -> {
            try {
                saveCallback.save(productDetails);
                close();
            } catch (RuntimeException e) {
                errorCallback.handleException(e);
            }
        });
    }
// end::snippet[]
}
```

1. Ce callback de sauvegarde n’a pas besoin de renvoyer un objet, puisque le dialog se ferme en cas de succès.

2. Créez un nouvel objet de données de formulaire vide pour chaque instance du dialog.

3. C’est presque la même implémentation que dans `ProductFormDrawer`, mais au lieu de repeupler le formulaire avec un nouveau FDO, elle ferme le dialog.

Ensuite, implémentez les callbacks dans `ProductCatalogView` :

ProductCatalogView\.java

```java
package com.example.product;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.masterdetaillayout.MasterDetailLayout;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import org.springframework.dao.OptimisticLockingFailureException;

@Route("")
@PageTitle("Product Catalog")
class ProductCatalogView extends MasterDetailLayout {

    ProductCatalogView(ProductCatalogService service) {
        // Create components
        var searchField = new SearchField();

        var grid = new ProductCatalogGrid();
        grid.setItemsPageable(pageable -> service
            .findItems(searchField.getValue(), pageable)
        ).setIdentifierProvider(ProductCatalogItem::productId);

        var drawer = new ProductFormDrawer(productDetails -> {
            var saved = service.save(productDetails);
            grid.getDataProvider().refreshAll();
            return saved;
        }, productDetails -> {
            service.delete(productDetails);
            grid.deselectAll();
            grid.getDataProvider().refreshAll();
        }, this::handleException);

        searchField.addValueChangeListener(e ->
                grid.getDataProvider().refreshAll());

        grid.addSelectionListener(e -> {
            var productDetails = e.getFirstSelectedItem()
                .flatMap(item -> service.findDetailsById(item.productId()));
            productDetails.ifPresent(drawer::setProductDetails);
            setDetail(productDetails.isPresent() ? drawer : null);
        });
        addBackdropClickListener(e -> grid.deselectAll());
        addDetailEscapePressListener(e -> grid.deselectAll());

// tag::snippet[]
        var addButton = new Button("Add Product", e ->
            new AddProductDialog(
                productDetails -> {
                    service.save(productDetails); // (1)
                    grid.getDataProvider().refreshAll(); // (2)
                },
                this::handleException // (3)
            ).open()
        );
// end::snippet[]

        // Layout view
        setSizeFull();
        setDetailSize("300px");
        setExpandMaster(true);

        var toolbar = new HorizontalLayout();
        toolbar.setWidthFull();
        toolbar.addToStart(searchField);
        toolbar.addToEnd(addButton);

        var listLayout = new VerticalLayout(toolbar, grid);
        listLayout.setSizeFull();
        grid.setSizeFull();

        setMaster(listLayout);
    }

    private void handleException(RuntimeException exception) {
        if (exception instanceof OptimisticLockingFailureException) {
            new WarningNotification("Another user has edited the same product. "
                + "Please refresh and try again.").open();
        } else {
            // Delegate to Vaadin's default error handler
            throw exception;
        }
    }

    static class SearchField extends TextField {

        SearchField() {
            setPlaceholder("Search");
            setPrefixComponent(VaadinIcon.SEARCH.create());
            setValueChangeMode(ValueChangeMode.LAZY);
        }
    }

    static class WarningNotification extends Notification {

        WarningNotification(String text) {
            super(text, 3000, Position.MIDDLE);
            addThemeVariants(NotificationVariant.WARNING);
        }
    }
}
```

1. Appelez le service pour valider le produit et l’insérer dans la base de données.

2. Rafraîchissez le grid afin que le nouveau produit apparaisse.

3. Réutilisez la méthode `handleException()` pour la gestion des erreurs.

Vous devriez maintenant pouvoir ajouter de nouveaux produits à la base de données, et ils devraient apparaître dans le grid.

## <a id="améliorer-lexpérience-utilisateur"></a>Améliorer l’expérience utilisateur

Lorsque vous avez implémenté la prise en charge de la modification dans l’étape précédente du tutoriel, vous êtes tombé sur certains problèmes d’expérience utilisateur et vous les avez corrigés. Vous allez maintenant corriger deux autres problèmes.

Vous avez peut-être remarqué que chaque nouvel élément est ajouté en bas du grid, sauf si un tri explicite a été appliqué sur une colonne particulière. Cela s’explique par le fait que le grid est trié par ID par défaut. Vous devez faire défiler vers le bas pour voir si l’élément a réellement été ajouté. Cela crée une confusion inutile pour l’utilisateur et pourrait être amélioré.

Ensuite, essayez d’insérer un produit avec le Stock Keeping Unit (SKU) suivant : `NBK-A5-DOT`

Le dialog devrait rester ouvert et, dans la sortie console, vous devriez voir l’erreur suivante :

```
org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation: "PUBLIC.CONSTRAINT_F2 INDEX PUBLIC.CONSTRAINT_INDEX_F ON PUBLIC.PRODUCTS(SKU NULLS FIRST) VALUES ( /* 2 */ 'NBK-A5-DOT' )";
```

C’est un autre exemple d’erreur récupérable déclenchée par une action utilisateur, et elle doit être traitée.

### <a id="sélectionner-lélément-ajouté"></a>Sélectionner l’élément ajouté

Pour rendre l’expérience moins déroutante pour les utilisateurs, vous allez sélectionner l’élément nouvellement ajouté après avoir rafraîchi le grid du catalogue de produits. Cependant, comme le grid contient des objets de type `ProductCatalogItem`, et que le formulaire utilise `ProductDetails`, vous devez trouver l’élément correspondant à sélectionner.

Pour ce faire, vous devez d’abord ajouter une nouvelle méthode `findById` à `ProductCatalogItemRepository` :

ProductCatalogItemRepository.java

```java
package com.example.product;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.repository.PagingAndSortingRepository;

// tag::snippet[]
import java.util.Optional;
// end::snippet[]

interface ProductCatalogItemRepository
    extends PagingAndSortingRepository<ProductCatalogItem, Long> {

// tag::snippet[]
    Optional<ProductCatalogItem> findById(Long id);
// end::snippet[]
    Slice<ProductCatalogItem> findByNameContainingIgnoreCase(String name,
        Pageable pageable);
}
```

Spring Data implémente automatiquement la méthode pour vous.

Ensuite, rendez la méthode disponible pour la vue en ajoutant une méthode `findItemById` à `ProductCatalogService` :

ProductCatalogService.java

```java
package com.example.product;

import jakarta.validation.Valid;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.Optional;

@Service
@Validated
@Transactional(readOnly = true)
class ProductCatalogService {

    private final ProductCatalogItemRepository productCatalogItemRepository;
    private final ProductDetailsRepository productDetailsRepository;

    public ProductCatalogService(
            ProductCatalogItemRepository productCatalogItemRepository,
            ProductDetailsRepository productDetailsRepository) {
        this.productCatalogItemRepository = productCatalogItemRepository;
        this.productDetailsRepository = productDetailsRepository;
    }

    public List<ProductCatalogItem> findItems(String searchTerm,
            Pageable pageable) {
        return productCatalogItemRepository
            .findByNameContainingIgnoreCase(searchTerm, pageable).getContent();
    }

    public Optional<ProductDetails> findDetailsById(Long id) {
        return productDetailsRepository.findById(id);
    }

// tag::snippet[]
    public Optional<ProductCatalogItem> findItemById(Long id) {
        return productCatalogItemRepository.findById(id);
    }
// end::snippet[]

    @Transactional
    public ProductDetails save(@Valid ProductDetails productDetails) {
        return productDetailsRepository.save(productDetails);
    }

    @Transactional
    public void delete(ProductDetails productDetails) {
        productDetailsRepository.delete(productDetails);
    }
}
```

Ensuite, appelez la méthode pour récupérer le `ProductCatalogItem` après avoir inséré un nouveau `ProductDetails`. Modifiez le callback de sauvegarde dans `ProductCatalogView` comme suit :

ProductCatalogView\.java

```java
package com.example.product;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.masterdetaillayout.MasterDetailLayout;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import org.springframework.dao.OptimisticLockingFailureException;

@Route("")
@PageTitle("Product Catalog")
class ProductCatalogView extends MasterDetailLayout {

    ProductCatalogView(ProductCatalogService service) {
        // Create components
        var searchField = new SearchField();

        var grid = new ProductCatalogGrid();
        grid.setItemsPageable(pageable -> service
            .findItems(searchField.getValue(), pageable)
        ).setIdentifierProvider(ProductCatalogItem::productId);

        var drawer = new ProductFormDrawer(productDetails -> {
            var saved = service.save(productDetails);
            grid.getDataProvider().refreshAll();
            return saved;
        }, productDetails -> {
            service.delete(productDetails);
            grid.deselectAll();
            grid.getDataProvider().refreshAll();
        }, this::handleException);

        searchField.addValueChangeListener(e ->
                grid.getDataProvider().refreshAll());

        grid.addSelectionListener(e -> {
            var productDetails = e.getFirstSelectedItem()
                .flatMap(item -> service.findDetailsById(item.productId()));
            productDetails.ifPresent(drawer::setProductDetails);
            setDetail(productDetails.isPresent() ? drawer : null);
        });
        addBackdropClickListener(e -> grid.deselectAll());
        addDetailEscapePressListener(e -> grid.deselectAll());

        var addButton = new Button("Add Product", e ->
            new AddProductDialog(
                productDetails -> {
// tag::snippet[]
                    var saved = service.save(productDetails);
                    grid.getDataProvider().refreshAll();
                    service.findItemById(saved.getProductId())
                           .ifPresent(grid::select);
// end::snippet[]
                },
                this::handleException
            ).open()
        );

        // Layout view
        setSizeFull();
        setDetailSize("300px");
        setExpandMaster(true);

        var toolbar = new HorizontalLayout();
        toolbar.setWidthFull();
        toolbar.addToStart(searchField);
        toolbar.addToEnd(addButton);

        var listLayout = new VerticalLayout(toolbar, grid);
        listLayout.setSizeFull();
        grid.setSizeFull();

        setMaster(listLayout);
    }

    private void handleException(RuntimeException exception) {
        if (exception instanceof OptimisticLockingFailureException) {
            new WarningNotification("Another user has edited the same product. "
                + "Please refresh and try again.").open();
        } else {
            // Delegate to Vaadin's default error handler
            throw exception;
        }
    }

    static class SearchField extends TextField {

        SearchField() {
            setPlaceholder("Search");
            setPrefixComponent(VaadinIcon.SEARCH.create());
            setValueChangeMode(ValueChangeMode.LAZY);
        }
    }

    static class WarningNotification extends Notification {

        WarningNotification(String text) {
            super(text, 3000, Position.MIDDLE);
            addThemeVariants(NotificationVariant.WARNING);
        }
    }
}
```

Redémarrez l’application, puisque vous avez modifié une interface de repository. Désormais, lorsque vous ajoutez un nouveau produit, il devrait être automatiquement sélectionné et apparaître dans le drawer.

### <a id="gérer-la-violation-de-contrainte"></a>Gérer la violation de contrainte

Ensuite, vous allez gérer le SKU en double. Spring traduit les erreurs de base de données dans sa propre hiérarchie d’exceptions, et signale une violation d’une contrainte unique sous la forme d’une `DuplicateKeyException`. Comme `sku` est la seule colonne unique dans la table `PRODUCTS` en dehors de l’ID généré, une `DuplicateKeyException` lors de la sauvegarde d’un produit signifie que le SKU est déjà utilisé.

Interceptez `DuplicateKeyException` plutôt que sa superclasse, `DataIntegrityViolationException`. La superclasse couvre aussi d’autres violations, comme un prix négatif, et les signaler comme un SKU en double embrouillerait l’utilisateur. Comme le service valide l’entrée, de telles violations ne devraient pas atteindre la base de données. Si cela arrive, c’est un bug, et cela doit être géré par le gestionnaire d’erreurs par défaut de Vaadin.

Mettez à jour la méthode `handleException()` dans `ProductCatalogView` comme suit. Le nouvel avertissement utilise `WarningNotification`, comme l’avertissement concernant le verrouillage optimiste, afin qu’il ait le même aspect :

ProductCatalogView\.java

```java
package com.example.product;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.masterdetaillayout.MasterDetailLayout;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
// tag::snippet[]
import org.springframework.dao.DuplicateKeyException;
// end::snippet[]
import org.springframework.dao.OptimisticLockingFailureException;

@Route("")
@PageTitle("Product Catalog")
class ProductCatalogView extends MasterDetailLayout {

    ProductCatalogView(ProductCatalogService service) {
        // Create components
        var searchField = new SearchField();

        var grid = new ProductCatalogGrid();
        grid.setItemsPageable(pageable -> service
            .findItems(searchField.getValue(), pageable)
        ).setIdentifierProvider(ProductCatalogItem::productId);

        var drawer = new ProductFormDrawer(productDetails -> {
            var saved = service.save(productDetails);
            grid.getDataProvider().refreshAll();
            return saved;
        }, productDetails -> {
            service.delete(productDetails);
            grid.deselectAll();
            grid.getDataProvider().refreshAll();
        }, this::handleException);

        searchField.addValueChangeListener(e ->
                grid.getDataProvider().refreshAll());

        grid.addSelectionListener(e -> {
            var productDetails = e.getFirstSelectedItem()
                .flatMap(item -> service.findDetailsById(item.productId()));
            productDetails.ifPresent(drawer::setProductDetails);
            setDetail(productDetails.isPresent() ? drawer : null);
        });
        addBackdropClickListener(e -> grid.deselectAll());
        addDetailEscapePressListener(e -> grid.deselectAll());

        var addButton = new Button("Add Product", e ->
            new AddProductDialog(
                productDetails -> {
                    var saved = service.save(productDetails);
                    grid.getDataProvider().refreshAll();
                    service.findItemById(saved.getProductId())
                           .ifPresent(grid::select);
                },
                this::handleException
            ).open()
        );

        // Layout view
        setSizeFull();
        setDetailSize("300px");
        setExpandMaster(true);

        var toolbar = new HorizontalLayout();
        toolbar.setWidthFull();
        toolbar.addToStart(searchField);
        toolbar.addToEnd(addButton);

        var listLayout = new VerticalLayout(toolbar, grid);
        listLayout.setSizeFull();
        grid.setSizeFull();

        setMaster(listLayout);
    }

    private void handleException(RuntimeException exception) {
        if (exception instanceof OptimisticLockingFailureException) {
            new WarningNotification("Another user has edited the same product. "
                + "Please refresh and try again.").open();
// tag::snippet[]
        } else if (exception instanceof DuplicateKeyException) {
            new WarningNotification(
                "The SKU is already in use. Please enter another one.").open();
// end::snippet[]
        } else {
            // Delegate to Vaadin's default error handler
            throw exception;
        }
    }

    static class SearchField extends TextField {

        SearchField() {
            setPlaceholder("Search");
            setPrefixComponent(VaadinIcon.SEARCH.create());
            setValueChangeMode(ValueChangeMode.LAZY);
        }
    }

    static class WarningNotification extends Notification {

        WarningNotification(String text) {
            super(text, 3000, Position.MIDDLE);
            addThemeVariants(NotificationVariant.WARNING);
        }
    }
}
```

Essayez maintenant de créer un nouvel élément avec le SKU `NBK-A5-DOT`. Vous devriez recevoir une notification vous demandant de saisir un autre SKU. Saisissez-en un autre et cliquez sur save. Cela aurait dû fonctionner, n’est-ce pas ? Mais ce n’est pas le cas. À la place, vous avez obtenu une notification différente :

```
Another user has edited the same product. Please refresh and try again.
```

Comment est-ce possible ? Comment un autre utilisateur peut-il avoir modifié un produit que vous n’avez même pas encore inséré ?

Vous venez de rencontrer un problème qui peut se produire chaque fois qu’un formulaire continue de modifier le même objet mutable à travers plusieurs sauvegardes, comme `ProductDetails` dans ce cas. Spring Data modifie l’objet pendant la sauvegarde, et une transaction annulée ne défait pas cette modification.

Voici ce qui s’est passé :

1. Vous avez cliqué sur **Save** avec un SKU en double.

2. Spring Data a tenté d’insérer le produit et a défini son numéro de version à 1.

3. La base de données a rejeté l’insertion à cause du SKU en double, et la transaction a été annulée.

4. **Cependant, l’objet `ProductDetails` en mémoire n’a pas été annulé** - il a toujours version=1.

5. Vous avez modifié le SKU et cliqué à nouveau sur **Save**.

6. Spring Data a vu que la version était déjà définie et a supposé qu’il s’agissait d’une entité *existante* à mettre à jour, et non d’une nouvelle.

7. La mise à jour a échoué car aucune ligne de ce type n’existe dans la base de données — d’où l’erreur de verrouillage optimiste.

Si cela avait été une API REST, l’objet `ProductDetails` aurait toujours été une nouvelle instance et cela n’aurait pas posé de problème. Comme vous réutilisez l’objet, vous devez contourner ce problème. Vous pouvez le faire de différentes manières, mais l’interface utilisateur ne devrait pas avoir à connaître l’une d’entre elles. C’est un détail de persistance, et la vue enregistre déjà les produits via `ProductCatalogService`. Cela fait du service le bon endroit pour le contournement.=== Enregistrer une copie du produit

Les moyens les plus simples d’éviter ce problème sont les suivants :

1. Définir la version sur `null` avant d’enregistrer un élément qui n’a pas encore d’ID.

2. Créer une copie de l’objet et transmettre la copie au repository, puis la renvoyer en cas de succès.

Créer une copie est plus élégant, car cela garantit que l’objet d’origine reste inchangé jusqu’à ce que la transaction soit validée avec succès. Cela suit un principe consistant à conserver les objets de données immuables pendant les opérations incertaines. De plus, vous avez déjà conçu vos callbacks d’UI pour prendre en charge des backends qui renvoient de nouvelles instances d’objets de données après leur enregistrement.

Ce problème est le coût de l’utilisation de l’entité comme FDO. Un FDO séparé l’éviterait également, car le formulaire ne détiendrait jamais l’objet que Spring Data modifie. Copier l’entité avant l’enregistrement offre la même protection sans seconde classe, ce qui est suffisant tant que le formulaire et la table correspondent un-à-un.

Commencez par ajouter deux constructeurs à `ProductDetails` - un *constructeur par défaut* pour créer de nouvelles instances, et un *constructeur de copie* pour créer des copies :

ProductDetails.java

```java
package com.example.product;

import jakarta.validation.constraints.DecimalMax;
import jakarta.validation.constraints.DecimalMin;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.PositiveOrZero;
import jakarta.validation.constraints.Size;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.relational.core.mapping.Table;

import java.math.BigDecimal;
import java.time.LocalDate;

@Table("PRODUCTS")
class ProductDetails {

    @Id
    private Long productId;
    @Version
    private Long version;
    @NotBlank @Size(max = 100)
    private String name;
    @NotBlank @Size(max = 500)
    private String description;
    @NotBlank @Size(max = 100)
    private String category;
    @Size(max = 100)
    private String brand;
    @NotBlank @Size(max = 50)
    private String sku;
    private LocalDate releaseDate;
    @NotNull @PositiveOrZero
    private BigDecimal price;
    @DecimalMin("0") @DecimalMax("100")
    private BigDecimal discount;

// tag::snippet[]
    public ProductDetails() {
    }

    public ProductDetails(ProductDetails original) {
        this.productId = original.productId;
        this.version = original.version;
        this.name = original.name;
        this.description = original.description;
        this.category = original.category;
        this.brand = original.brand;
        this.sku = original.sku;
        this.releaseDate = original.releaseDate;
        this.price = original.price;
        this.discount = original.discount;
    }
// end::snippet[]

    public Long getProductId() {
        return productId;
    }

    public Long getVersion() {
        return version;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getSku() {
        return sku;
    }

    public void setSku(String sku) {
        this.sku = sku;
    }

    public LocalDate getReleaseDate() {
        return releaseDate;
    }

    public void setReleaseDate(LocalDate releaseDate) {
        this.releaseDate = releaseDate;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public BigDecimal getDiscount() {
        return discount;
    }

    public void setDiscount(BigDecimal discount) {
        this.discount = discount;
    }
}
```

Ensuite, mettez à jour `ProductCatalogService` afin qu’il transmette une copie de `ProductDetails` au repository :

ProductCatalogService.java

```java
package com.example.product;

import jakarta.validation.Valid;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.Optional;

@Service
@Validated
@Transactional(readOnly = true)
class ProductCatalogService {

    private final ProductCatalogItemRepository productCatalogItemRepository;
    private final ProductDetailsRepository productDetailsRepository;

    public ProductCatalogService(
            ProductCatalogItemRepository productCatalogItemRepository,
            ProductDetailsRepository productDetailsRepository) {
        this.productCatalogItemRepository = productCatalogItemRepository;
        this.productDetailsRepository = productDetailsRepository;
    }

    public List<ProductCatalogItem> findItems(String searchTerm,
            Pageable pageable) {
        return productCatalogItemRepository
            .findByNameContainingIgnoreCase(searchTerm, pageable).getContent();
    }

    public Optional<ProductDetails> findDetailsById(Long id) {
        return productDetailsRepository.findById(id);
    }

    public Optional<ProductCatalogItem> findItemById(Long id) {
        return productCatalogItemRepository.findById(id);
    }

    @Transactional
    public ProductDetails save(@Valid ProductDetails productDetails) {
// tag::snippet[]
        return productDetailsRepository.save(new ProductDetails(productDetails));
// end::snippet[]
    }

    @Transactional
    public void delete(ProductDetails productDetails) {
        productDetailsRepository.delete(productDetails);
    }
}
```

Essayez maintenant d’insérer à nouveau un élément produit avec un SKU existant. Vous devriez recevoir la notification d’erreur, comme prévu. Ensuite, modifiez le SKU pour qu’il soit unique et enregistrez l’élément. Tout devrait fonctionner comme prévu.

## <a id="code-complet-pour-cette-étape"></a>Code complet pour cette étape

Si votre application ne se comporte pas comme décrit, comparez vos fichiers avec ces listings. Ils montrent chaque classe de l’application telle qu’elle devrait apparaître à la fin de cette étape.

La [`step/add-data` branch](https://github.com/vaadin/tutorial/tree/step/add-data) du repository `vaadin/tutorial` sur GitHub contient l’intégralité du projet tel qu’il se présente à la fin de cette étape.

ProductCatalogView\.java

```java
package com.example.product;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.masterdetaillayout.MasterDetailLayout;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.OptimisticLockingFailureException;

@Route("")
@PageTitle("Product Catalog")
class ProductCatalogView extends MasterDetailLayout {

    ProductCatalogView(ProductCatalogService service) {
        // Create components
        var searchField = new SearchField();

        var grid = new ProductCatalogGrid();
        grid.setItemsPageable(pageable -> service
            .findItems(searchField.getValue(), pageable)
        ).setIdentifierProvider(ProductCatalogItem::productId);

        var drawer = new ProductFormDrawer(productDetails -> {
            var saved = service.save(productDetails);
            grid.getDataProvider().refreshAll();
            return saved;
        }, productDetails -> {
            service.delete(productDetails);
            grid.deselectAll();
            grid.getDataProvider().refreshAll();
        }, this::handleException);

        searchField.addValueChangeListener(e ->
                grid.getDataProvider().refreshAll());

        grid.addSelectionListener(e -> {
            var productDetails = e.getFirstSelectedItem()
                .flatMap(item -> service.findDetailsById(item.productId()));
            productDetails.ifPresent(drawer::setProductDetails);
            setDetail(productDetails.isPresent() ? drawer : null);
        });
        addBackdropClickListener(e -> grid.deselectAll());
        addDetailEscapePressListener(e -> grid.deselectAll());

        var addButton = new Button("Add Product", e ->
            new AddProductDialog(
                productDetails -> {
                    var saved = service.save(productDetails);
                    grid.getDataProvider().refreshAll();
                    service.findItemById(saved.getProductId())
                           .ifPresent(grid::select);
                },
                this::handleException
            ).open()
        );

        // Layout view
        setSizeFull();
        setDetailSize("300px");
        setExpandMaster(true);

        var toolbar = new HorizontalLayout();
        toolbar.setWidthFull();
        toolbar.addToStart(searchField);
        toolbar.addToEnd(addButton);

        var listLayout = new VerticalLayout(toolbar, grid);
        listLayout.setSizeFull();
        grid.setSizeFull();

        setMaster(listLayout);
    }

    private void handleException(RuntimeException exception) {
        if (exception instanceof OptimisticLockingFailureException) {
            new WarningNotification("Another user has edited the same product. "
                + "Please refresh and try again.").open();
        } else if (exception instanceof DuplicateKeyException) {
            new WarningNotification(
                "The SKU is already in use. Please enter another one.").open();
        } else {
            // Delegate to Vaadin's default error handler
            throw exception;
        }
    }

    static class SearchField extends TextField {

        SearchField() {
            setPlaceholder("Search");
            setPrefixComponent(VaadinIcon.SEARCH.create());
            setValueChangeMode(ValueChangeMode.LAZY);
        }
    }

    static class WarningNotification extends Notification {

        WarningNotification(String text) {
            super(text, 3000, Position.MIDDLE);
            addThemeVariants(NotificationVariant.WARNING);
        }
    }
}
```

ProductCatalogGrid.java

```java
package com.example.product;

import com.vaadin.flow.component.grid.ColumnTextAlign;
import com.vaadin.flow.component.grid.Grid;

class ProductCatalogGrid extends Grid<ProductCatalogItem> {

    ProductCatalogGrid() {
        addColumn(ProductCatalogItem::name)
            .setHeader("Name")
            .setSortProperty(ProductCatalogItem.SORT_PROPERTY_NAME);
        addColumn(ProductCatalogItem::price)
            .setHeader("Price")
            .setTextAlign(ColumnTextAlign.END)
            .setSortProperty(ProductCatalogItem.SORT_PROPERTY_PRICE);
        addColumn(ProductCatalogItem::description)
            .setHeader("Description")
            .setSortProperty(ProductCatalogItem.SORT_PROPERTY_DESCRIPTION);
        addColumn(ProductCatalogItem::category)
            .setHeader("Category")
            .setSortProperty(ProductCatalogItem.SORT_PROPERTY_CATEGORY);
        addColumn(ProductCatalogItem::brand)
            .setHeader("Brand")
            .setSortProperty(ProductCatalogItem.SORT_PROPERTY_BRAND);
    }
}
```

ProductCatalogItem.java

```java
package com.example.product;

import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;

import java.math.BigDecimal;

@Table("PRODUCTS")
record ProductCatalogItem(
        @Id long productId,
        String name,
        String description,
        String category,
        String brand,
        BigDecimal price
) {
    static final String SORT_PROPERTY_NAME = "name";
    static final String SORT_PROPERTY_PRICE = "price";
    static final String SORT_PROPERTY_DESCRIPTION = "description";
    static final String SORT_PROPERTY_CATEGORY = "category";
    static final String SORT_PROPERTY_BRAND = "brand";
}
```

ProductCatalogItemRepository.java

```java
package com.example.product;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.repository.PagingAndSortingRepository;

import java.util.Optional;

interface ProductCatalogItemRepository
    extends PagingAndSortingRepository<ProductCatalogItem, Long> {

    Optional<ProductCatalogItem> findById(Long id);
    Slice<ProductCatalogItem> findByNameContainingIgnoreCase(String name,
        Pageable pageable);
}
```

ProductCatalogService.java

```java
package com.example.product;

import jakarta.validation.Valid;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.Optional;

@Service
@Validated
@Transactional(readOnly = true)
class ProductCatalogService {

    private final ProductCatalogItemRepository productCatalogItemRepository;
    private final ProductDetailsRepository productDetailsRepository;

    public ProductCatalogService(
            ProductCatalogItemRepository productCatalogItemRepository,
            ProductDetailsRepository productDetailsRepository) {
        this.productCatalogItemRepository = productCatalogItemRepository;
        this.productDetailsRepository = productDetailsRepository;
    }

    public List<ProductCatalogItem> findItems(String searchTerm,
            Pageable pageable) {
        return productCatalogItemRepository
            .findByNameContainingIgnoreCase(searchTerm, pageable).getContent();
    }

    public Optional<ProductDetails> findDetailsById(Long id) {
        return productDetailsRepository.findById(id);
    }

    public Optional<ProductCatalogItem> findItemById(Long id) {
        return productCatalogItemRepository.findById(id);
    }

    @Transactional
    public ProductDetails save(@Valid ProductDetails productDetails) {
        return productDetailsRepository.save(new ProductDetails(productDetails));
    }

    @Transactional
    public void delete(ProductDetails productDetails) {
        productDetailsRepository.delete(productDetails);
    }
}
```

ProductDetails.java

```java
package com.example.product;

import jakarta.validation.constraints.DecimalMax;
import jakarta.validation.constraints.DecimalMin;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.PositiveOrZero;
import jakarta.validation.constraints.Size;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.relational.core.mapping.Table;

import java.math.BigDecimal;
import java.time.LocalDate;

@Table("PRODUCTS")
class ProductDetails {

    @Id
    private Long productId;
    @Version
    private Long version;
    @NotBlank @Size(max = 100)
    private String name;
    @NotBlank @Size(max = 500)
    private String description;
    @NotBlank @Size(max = 100)
    private String category;
    @Size(max = 100)
    private String brand;
    @NotBlank @Size(max = 50)
    private String sku;
    private LocalDate releaseDate;
    @NotNull @PositiveOrZero
    private BigDecimal price;
    @DecimalMin("0") @DecimalMax("100")
    private BigDecimal discount;

    public ProductDetails() {
    }

    public ProductDetails(ProductDetails original) {
        this.productId = original.productId;
        this.version = original.version;
        this.name = original.name;
        this.description = original.description;
        this.category = original.category;
        this.brand = original.brand;
        this.sku = original.sku;
        this.releaseDate = original.releaseDate;
        this.price = original.price;
        this.discount = original.discount;
    }

    public Long getProductId() {
        return productId;
    }

    public Long getVersion() {
        return version;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getSku() {
        return sku;
    }

    public void setSku(String sku) {
        this.sku = sku;
    }

    public LocalDate getReleaseDate() {
        return releaseDate;
    }

    public void setReleaseDate(LocalDate releaseDate) {
        this.releaseDate = releaseDate;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public BigDecimal getDiscount() {
        return discount;
    }

    public void setDiscount(BigDecimal discount) {
        this.discount = discount;
    }
}
```

ProductDetailsRepository.java

```java
package com.example.product;

import org.springframework.data.repository.CrudRepository;

interface ProductDetailsRepository
    extends CrudRepository<ProductDetails, Long> {
}
```

ProductForm.java

```java
package com.example.product;

import com.vaadin.flow.component.Composite;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.textfield.BigDecimalField;
import com.vaadin.flow.component.textfield.TextArea;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.validator.BigDecimalRangeValidator;
import org.jspecify.annotations.Nullable;

import java.math.BigDecimal;
import java.util.Optional;

class ProductForm extends Composite<FormLayout>  {

    private final Binder<ProductDetails> binder;

    ProductForm() {
        // Create components
        var nameField = new TextField("Name");
        nameField.setMaxLength(100);
        var descriptionField = new TextArea("Description");
        descriptionField.setMaxLength(500);
        var categoryField = new TextField("Category");
        categoryField.setMaxLength(100);
        var brandField = new TextField("Brand");
        brandField.setMaxLength(100);
        var skuField = new TextField("SKU");
        skuField.setMaxLength(50);
        var releaseDateField = new DatePicker("Release Date");
        var priceField = new BigDecimalField("Price");
        var discountField = new BigDecimalField("Discount");
        discountField.setSuffixComponent(new Span("%"));

        // Layout form
        var layout = getContent();
        layout.add(nameField);
        layout.add(descriptionField);
        layout.add(categoryField);
        layout.add(brandField);
        layout.add(skuField);
        layout.add(releaseDateField);
        layout.add(priceField);
        layout.add(discountField);

        // Bind fields
        binder = new Binder<>();
        binder.forField(nameField)
              .asRequired("Enter name")
              .bind(ProductDetails::getName,
                    ProductDetails::setName);
        binder.forField(descriptionField)
              .asRequired("Enter description")
              .bind(ProductDetails::getDescription,
                    ProductDetails::setDescription);
        binder.forField(categoryField)
              .asRequired("Enter category")
              .bind(ProductDetails::getCategory,
                    ProductDetails::setCategory);
        binder.forField(brandField)
              .bind(ProductDetails::getBrand,
                    ProductDetails::setBrand);
        binder.forField(skuField)
              .asRequired("Enter SKU")
              .bind(ProductDetails::getSku,
                    ProductDetails::setSku);
        binder.forField(releaseDateField)
              .bind(ProductDetails::getReleaseDate,
                    ProductDetails::setReleaseDate);
        binder.forField(priceField)
              .asRequired("Enter price")
              .withValidator(new BigDecimalRangeValidator(
                  "Enter a price of 0 or more", BigDecimal.ZERO, null))
              .bind(ProductDetails::getPrice,
                    ProductDetails::setPrice);
        binder.forField(discountField)
              .withValidator(new BigDecimalRangeValidator(
                  "Enter a discount between 0 and 100",
                  BigDecimal.ZERO, BigDecimal.valueOf(100)))
              .bind(ProductDetails::getDiscount,
                    ProductDetails::setDiscount);
    }

    public void setFormDataObject(@Nullable ProductDetails productDetails) {
        binder.setBean(productDetails);
    }

    public Optional<ProductDetails> getFormDataObject() {
        if (binder.getBean() == null) {
            throw new IllegalStateException("No form data object");
        }
        if (binder.validate().isOk()) {
            return Optional.of(binder.getBean());
        } else {
            return Optional.empty();
        }
    }
}
```

ProductFormDrawer.java

```java
package com.example.product;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.confirmdialog.ConfirmDialog;
import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.Scroller;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;

class ProductFormDrawer extends VerticalLayout {

    @FunctionalInterface
    interface SaveCallback {
        ProductDetails save(ProductDetails productDetails);
    }

    @FunctionalInterface
    interface DeleteCallback {
        void delete(ProductDetails productDetails);
    }

    @FunctionalInterface
    interface ErrorCallback {
        void handleException(RuntimeException e);
    }

    private final SaveCallback saveCallback;
    private final DeleteCallback deleteCallback;
    private final ErrorCallback errorCallback;
    private final ProductForm form;
    private ProductDetails productDetails;

    ProductFormDrawer(SaveCallback saveCallback, DeleteCallback deleteCallback,
                      ErrorCallback errorCallback) {
        this.saveCallback = saveCallback;
        this.deleteCallback = deleteCallback;
        this.errorCallback = errorCallback;

        var header = new H2("Product Details");
        form = new ProductForm();

        var saveButton = new Button("Save", e -> save());
        saveButton.addThemeVariants(ButtonVariant.PRIMARY);
        var deleteButton = new Button("Delete", e -> delete());
        deleteButton.addThemeVariants(ButtonVariant.ERROR);

        add(header);
        add(new Scroller(form));
        add(new HorizontalLayout(saveButton, deleteButton));
        setHeightFull();
    }

    public void setProductDetails(ProductDetails productDetails) {
        this.productDetails = productDetails;
        form.setFormDataObject(productDetails);
    }

    private void save() {
        form.getFormDataObject().ifPresent(productDetails -> {
            try {
                var saved = saveCallback.save(productDetails);
                setProductDetails(saved);
            } catch (RuntimeException e) {
                errorCallback.handleException(e);
            }
        });
    }

    private void delete() {
        new DeleteProductDialog(() -> {
            try {
                deleteCallback.delete(productDetails);
            } catch (RuntimeException e) {
                errorCallback.handleException(e);
            }
        }).open();
    }

    static class DeleteProductDialog extends ConfirmDialog {

        DeleteProductDialog(Runnable onDelete) {
            super("Delete Product",
                "Are you sure you want to permanently delete this product?",
                "Delete", e -> onDelete.run());
            setCancelable(true);
            setConfirmButtonTheme("error primary");
        }
    }
}
```

AddProductDialog.java

```java
package com.example.product;

import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.dialog.Dialog;

class AddProductDialog extends Dialog {

    @FunctionalInterface
    interface SaveCallback {
        void save(ProductDetails productDetails);
    }

    @FunctionalInterface
    interface ErrorCallback {
        void handleException(RuntimeException e);
    }
    private final SaveCallback saveCallback;
    private final ErrorCallback errorCallback;
    private final ProductForm form;

    AddProductDialog(SaveCallback saveCallback, ErrorCallback errorCallback) {
        this.saveCallback = saveCallback;
        this.errorCallback = errorCallback;

        // Create components
        form = new ProductForm();
        form.setFormDataObject(new ProductDetails());
        var saveButton = new Button("Save", e -> save());
        saveButton.addThemeVariants(ButtonVariant.PRIMARY);
        var cancelButton = new Button("Cancel", e -> close());

        // Layout dialog
        setHeaderTitle("Add Product");
        add(form);
        getFooter().add(cancelButton, saveButton);
    }

    private void save() {
        form.getFormDataObject().ifPresent(productDetails -> {
            try {
                saveCallback.save(productDetails);
                close();
            } catch (RuntimeException e) {
                errorCallback.handleException(e);
            }
        });
    }
}
```

## <a id="étapes-suivantes"></a>Étapes suivantes

Vous avez maintenant construit une application Spring Boot entièrement fonctionnelle avec une UI Vaadin. Elle possède les fonctionnalités suivantes :

- Chargement de données paginé

- Tri et filtrage

- Formulaires et validation

- Modification, insertion, et suppression

Vous avez également refactorisé et amélioré la structure du code au fur et à mesure que de nouvelles fonctionnalités et des bugs sont apparus. Bien que cet exemple d’application soit assez simple, les modèles que vous avez appris sont tout aussi utiles dans des applications métier plus grandes, réelles.

Jusqu’à présent, l’application ne comporte qu’une seule vue. Ensuite, vous ajouterez un layout principal avec un menu de navigation, et une seconde vue vers laquelle naviguer. Passez à l’étape [Ajouter la navigation](https://vaadin.com/docs/latest/fr/getting-started/tutorial/add-navigation.md) pour continuer le tutoriel.

[Next: Add Navigation](../../getting-started/tutorial/add-navigation)
