Home > Software design >  How to restructure positions of product media or remove all images using product api in Shopware
How to restructure positions of product media or remove all images using product api in Shopware

Time:08-26

So I have an product and want to change the position of its images and swap the cover image, while adding some more images to the medias assigned to the product.
The media should look somewhat like this:

{
  "media": [
    {
      "id": "a060944a2938442c8d461b3a0107ecf5",
      "mediaId": "722d194bfbb84dc489f9f5b74da53bb3",
      "position": 1
    },
    {
      "id": "b060944a2938442c8d461b3a0107ecf6",
      "mediaId": "822d194bfbb84dc489f9f5b74da53bb4",
      "position": 2
    }
  ],
  "coverId": "a060944a2938442c8d461b3a0107ecf5"
}

and change to this:

{
  "media": [
    {
      "id": "a060944a2938442c8d461b3a0107ecf5",
      "mediaId": "722d194bfbb84dc489f9f5b74da53bb3",
      "position": 3
    },
    {
      "id": "b060944a2938442c8d461b3a0107ecf6",
      "mediaId": "822d194bfbb84dc489f9f5b74da53bb4",
      "position": 2
    },
    {
      "id": "c060944a2938442c8d461b3a0107ecf7",
      "mediaId": "922d194bfbb84dc489f9f5b74da53bb5",
      "position": 1
    }
  ],
  "coverId": "b060944a2938442c8d461b3a0107ecf6"
}

I couldn't find a way to restructure the media positions and change the cover image.
So I tried to remove the media from the product, but the cover image stills stays even though the medias aren't connected to the product any more.
Also an UPDATE on the coverId doesn't seem to do the job either.

I used this to remove the images:

DELETE https://your-page.com/api/product/5efd4f22dc134ba7bf77c85f92fed0a9/media/b060944a2938442c8d461b3a0107ecf6

CodePudding user response:

cover and media are two separate associations, so removing all media associations can still leave the cover association intact.

  • new ManyToOneAssociationField('cover', 'product_media_id', ProductMediaDefinition::class, 'id')
  • new OneToManyAssociationField('media', ProductMediaDefinition::class, 'product_id')

Notice how both refer to the definition ProductMediaDefinition. That means for coverId you have to provide the id of an existing product_media entity, not of a media entity.

If you have the id of a media entity, you can also create the product_media entity on the fly:

{
  "id": "{productId}",
  "cover": {
    "mediaId": "{mediaId}"
  }
}

If you want to remove the cover image without setting a new one, you can set coverId to null.

  • Related