How to create and update with the same form

Viewed 38

I use the repositoryFactory in a custom plugin's Vue file in Shopware 6. When I save an entity I do this:

this.settingsRepository
    .save(this.setting, Shopware.Context.api)
    .then((result) => {

In case the person sends the form and this function is called, I want to get back the id of the setting in case the person hit's the save button again. But then the entity needs to be updated and not created. As I see from the response, there is an id, but it's in config.data -> json serialised.

How's the default way of solving this issue?

1 Answers

The best practice would be to re-fetch the entity after persisting it. This is because some entities may have fields that get automatically computed or indexed server-side and you'd probably always want to have the entity in its actual current state. If you're absolutely sure you don't want to fetch the entity again, you could manually set the _isNew flag to false after persisting:

this.setting._isNew = false;

This will then cause the save function to use the update instead of the create route. Keep in mind that this is actually kind of an internal property, as there is no setter for it and as already mentioned fetching the entity again is encouraged.

Also you shouldn't have to worry about the id. It should've already been generated client-side and set to the entity, when using the repository to create a new entity like that:

this.setting = this.settingsRepository.create();
Related