0

I am running a website with 2 store views, and 1 website. I have products where images are already added. And image roles are assigned on "All Store Views", but roles have been deleted by the admin by mistake. I am writing a script to assign roles to them (store-wise) by taking the roles from the "All Store Views". Currently, my implementation is

$products = $this->getProductCollection()
foreach ($products->getAllIds() as $productId) {
   $product = $productRepository->getById($productId, false, 0, true);
   $mediaGalleryEntries = $product->getMediaGalleryEntries();
   if ($mediaGalleryEntries) {
      foreach ($storeManager->getStores() as $store) {
         /** @var Product $storeProduct */
         $storeProduct = $productRepository->getById($productId, true, $store->getId(), true);
         $entries = [];
         foreach ($mediaGalleryEntries as $mediaGalleryEntry) {
             $entries[] = $mediaGalleryEntry;
         }
        $storeProduct->setMediaGalleryEntries($entries);
        $productRepository->save($storeProduct);
        echo __("Product #%product_id from store %store_id saved for store %store_code\n", ['product_id' => $product->getId(), 'store_code' => $store->getCode(), 'store_id' => $storeProduct->getStoreId()]);
    }
  }
}

But it's not saving the image roles. No errors as well. Also, the weird thing is, sometimes it's saving only for the first store, but not the second store. What am I doing wrong here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.