1

I have deleted the product image using the following code

 $imageProcessor = $_objectManager->create('\Magento\Catalog\Model\Product\Gallery\Processor');
                $images = $product->getMediaGalleryImages();
                $productGallery = $_objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Gallery');
                foreach($images as $child) {
                    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                    $productGallery = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\Gallery');
                    $productGallery->deleteGallery($child['value_id']);
                    $product->setMediaGalleryEntries([]);
                    $imageProcessor->removeImage($product, $child['file']);
                    $product->save();
                }

Image successfully deleted.

enter image description here

But due to the thumbnail image existence, it is still shown in the product grid

enter image description here

Please help with how to get this thumbnail image and delete

I have tried following the way to get a thumbnail image, but no luck.

 $productData = $this->productFactory->create();
                $product = $productData->load(1884);
                print_r($product->getThumbnail());

It returns empty value, but the value exists in database table catalog_product_entity_varchar

enter image description here

So How do get the thumbnail image or small image of a product and how to empty its value and then save the product ?

1 Answer 1

3

Magento stores information about product image in 2 places

  1. In Gallery the list of available images for product with properties

  2. In catalog_product_entity_varchar the value selected for image type like thumbnail. Empty value should be no_selection

Magento uses data provider in UI listing and the value for grid comes from 2nd place

You need to reset all image types for product before save in your remove logic like

$product->setData('image', 'no_selection');
$product->setData('small_image','no_selection');
// $product->setData('swatch_image', 'no_selection');
$product->setData('thumbnail', 'no_selection');

// or you can use method getMediaAttributes for get all media attributes
foreach ($product->getMediaAttributes() as $attribute) {
    $product->setData($attribute->getAttributeCode(), 'no_selection');
}

also you can use logic from \Magento\Catalog\Model\Product\Gallery\CreateHandler

// this logic persist value in DB
$product->addAttributeUpdate(
    $mediaAttrCode,
    $newValue,
    $storeId
);
// receive raw value from DB
// \Magento\Catalog\Model\ResourceModel\Product
$thumbnail = $productResource->getAttributeRawValue($product->getId(),
    'thumbnail', $product->getStore());

[Update]

Helper to remove all product images. Just move to your namespace and try

<?php
declare(strict_types=1);

namespace Acme\StackExchange\Helper;

use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Gallery\Processor as ProcessorAlias;
use Magento\Catalog\Model\Product\Media\ConfigInterface as MediaConfigInterface;
use Magento\Catalog\Model\ProductRepository;
use Magento\Catalog\Model\ResourceModel\Product\Gallery as GalleryResource;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\Filesystem;
use Psr\Log\LoggerInterface;

class CatalogProduct extends AbstractHelper
{
    protected ProductRepository    $productRepository;
    protected GalleryResource      $galleryResource;
    protected ProcessorAlias       $galleryProcessor;
    protected MediaConfigInterface $mediaConfig;
    protected Filesystem           $filesystem;
    protected LoggerInterface      $logger;

    public function __construct(
        Context $context,
        ProductRepository $productRepository,
        GalleryResource $galleryResource,
        ProcessorAlias $galleryProcessor,
        MediaConfigInterface $mediaConfig,
        Filesystem $filesystem,
        LoggerInterface $logger
    ) {
        parent::__construct($context);

        $this->productRepository = $productRepository;
        $this->galleryResource   = $galleryResource;
        $this->galleryProcessor  = $galleryProcessor;
        $this->mediaConfig       = $mediaConfig;
        $this->filesystem        = $filesystem;
        $this->logger            = $logger;
    }

    public function deleteAllImages(int $productId, bool $physical = false)
    {
        /** @var Product $product */
        $product = $this->productRepository->getById($productId, true, 0);

        $valueIds    = [];
        $removeFiles = [];
        foreach ($product->getMediaGalleryImages() as $galleryImage) {
            $valueIds[]    = $galleryImage['value_id'];
            $removeFiles[] = $galleryImage['file'];
        }

        if ($valueIds) {
            $this->galleryResource->deleteGallery($valueIds);
        }

        foreach ($product->getMediaAttributes() as $attribute) {
            $value = $product->getData($attribute->getAttributeCode());
            // remove non-gallery image file
            if ($value && $value !== 'no_selection') {
                if (!in_array($value, $removeFiles, true)) {
                    $removeFiles[] = $value;
                }
            }
            $product->setData($attribute->getAttributeCode(), 'no_selection');
        }

        if ($physical) {
            $mediaDir  = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
            $mediaPath = $this->mediaConfig->getBaseMediaPath();

            foreach ($removeFiles as $removeFile) {
                if (!$this->galleryResource->countImageUses($removeFile)) {
                    $filePath = $mediaPath . $removeFile;
                    if ($mediaDir->isFile($filePath)) {
                        try {
                            $this->galleryProcessor->removeImage($product, $removeFile);
                            $mediaDir->delete($filePath);
                        } catch (\Exception $e) {
                            $this->logger->critical($e);
                        }
                    }
                }
            }
        }

        $product->unsetData('media_gallery');

        $this->productRepository->save($product);
    }
}

Using

// remove only values
$helper->deleteAllImages(1884);
// remove values and files
$helper->deleteAllImages(1884, true);
9
  • Hi @victor, I have tried your solution, but it si not working...even when i tried to get thumbnail value, it display no_selection......it is not fetching the actual thumbnail value
    – Jaisa
    Commented Jun 16, 2022 at 14:52
  • no_selection is designed value for empty image value. If you remove image in admin - you will receive the same value in DB. If you will use any system resources - the system will correct process it. If you have a customization, just add additional check for no_selection value. Or please update your question with more details what are you want to implement/cover. Commented Jun 16, 2022 at 14:57
  • Actually, i want to get image thumbnail image and want to emptied it and again need to save the product with empty or no_selection value
    – Jaisa
    Commented Jun 16, 2022 at 15:01
  • Is your code works in global or store scope? I see some logic mistakes in your fragment of code, but it's difficult to catch what are you want to implement with this fragment. Do you want to create a logic to remove all images for product? Correct? Commented Jun 16, 2022 at 15:08
  • Yes correct i want to remove all images of a product
    – Jaisa
    Commented Jun 16, 2022 at 15:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.