0

I am adding images to the products from a folder programmatically using addImageToMediaGallery function. below is my controller code

<?php
namespace Kammalou\AddMissingImages\Controller\Missing;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Context;

class Images extends \Magento\Framework\App\Action\Action
{
    protected $pageFactory;
    public function __construct(Context $context, PageFactory $pageFactory)
    {
        $this->pageFactory = $pageFactory;
        return parent::__construct($context);
    }

    public function execute()
    {        
        var_dump(__METHOD__);
        $page_object = $this->pageFactory->create();
        $obj = \Magento\Framework\App\ObjectManager::getInstance();
        $productCollection = $obj->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
        $collection = $productCollection->create()->addAttributeToSelect('*')->load();
    
    

        foreach ($collection as $product){
            $productId =  $product->getId() ; // Id of product
            $product = $obj->create('Magento\Catalog\Model\Product')->load($productId);
            $image = $product->getImage();
            if($image =='' || $image=='no_selection' ){
               // echo 'Name  =  '.$product->getName().'<br>';

                $imagePath = "/var/www/vhosts/m2atimedev/httpdocs/var/inriver/pics/".$product->getName().".jpg";                                                                                          
                // path of the image
                //echo $imagePath;exit;
                if(file_exists($imagePath)){
                    //Remove Images From Product
                    
                    $productRepository = $obj->create('Magento\Catalog\Api\ProductRepositoryInterface');
                    $existingMediaGalleryEntries = $product->getMediaGalleryEntries();
                    if($existingMediaGalleryEntries){
                        foreach ($existingMediaGalleryEntries as $key => $entry) {
                            unset($existingMediaGalleryEntries[$key]);
                        }
                    }
                    $product->setMediaGalleryEntries($existingMediaGalleryEntries);
                    $productRepository->save($product);

                    // Adding Image to product
                    $product = $obj->create('Magento\Catalog\Model\Product')->load($productId);
                    $product->addImageToMediaGallery($imagePath, array('image', 'small_image', 'thumbnail'), false, false);
                    $product->save();
                }
                //echo 'image  =  '.$product->getImage().'<br>';

            }
        }

        return $page_object;
    }
}

The code is working very fine. but the problem is when images are set as thumbnail only for default magento scope. In the store scope image is showing but not selected as thumbnails. enter image description here

when i change scope, the base small thumbnail image does not show selected. enter image description here

As a result in the frontend the images are not showing with the products on category and search results page. enter image description here

If we click on products with missing images, than on the product page images is showing correctly.

How to show images with products on category page programmatically. Right now i have to go to backend, select product, change scope to store and set base, small and thumbnail image.

2
  • does it throw any exceptions if not is the path correct??
    – Ghulam.M
    Mar 24 at 12:17
  • if(file_exists($imagePath)){ is already added in the code for that purpose. Mar 24 at 13:26
2

I have just a simple solution .I hope it work for you . On table catalog_product_entity_varchar

$tableName = 'catalog_product_entity_varchar';
$productId = '1';
try {
            $getimage = "SELECT value FROM " . $tableName . " WHERE `entity_id` = '$productId' AND `store_id` = '1' AND `attribute_id` = '85'";
            $imageUrl = $connection->fetchAll($getimage);
            $imagePath = $imageUrl[0]['value'];
            $sql = "DELETE FROM " . $tableName ." WHERE `entity_id`='$productId' AND `attribute_id` IN ('85','86','87')";
            $connection->query($sql);
            $sql1 = "INSERT INTO " . $tableName ." (`attribute_id`, `store_id`, `entity_id`, `value`) VALUES ('85','0','$productId','$imagePath'),('85','1','$productId','$imagePath'),('86','0','$productId','$imagePath'),('86','1','$productId','$imagePath'),('87','0','$productId','$imagePath'),('87','1','$productId','$imagePath')";
            echo $sql1;

}

Where 85,86,87 are code for base,small and thumnall resp. (for my case).

before run You should backup database and check that codes.

0

Some products who’s images were not showing have this kind of problem. to search thumbnail images

SELECT * FROM catalog_product_entity_varchar WHERE entity_id = 9676;

enter image description here

you can see for the website with id 1 the images records have saved “.jpeg” instead of .jpg and for default storeID 0, it was not the problem. So i changed jpeg to jpg using below query:

UPDATE catalog_product_entity_varchar SET value = REPLACE(value, '.jpeg', '.jpg') WHERE attribute_id IN (85,86,87);

I Run below query to change base small and thumbnail images from storeID 0 (default veiw) to storeID 1(example.com)

UPDATE IGNORE catalog_product_entity_varchar set store_id=1 WHERE attribute_id IN (85,86,87) AND store_id=0;

Problem was base small and thumbnail images were set for default view but not for example.com store view

Your Answer

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

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