1

I am trying to override the getGalleryImagesJson() method of Class

Magento\Catalog\Block\Product\View\Gallery

using plugin method but it is not working well.

Here are my codes:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Catalog\Block\Product\View\Gallery">
    <plugin name="custom_catalog_block_product_view_gallery"
            type="Custom\Catalog\Plugin\Catalog\Block\Product\View\Gallery" sortOrder="10" disabled="false" />
</type>

The overriden block file:

<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

/**
* Simple product data view
*
* @author     Magento Core Team <core@magentocommerce.com>
*/
namespace Custom\Catalog\Plugin\Catalog\Block\Product\View;

use Magento\Catalog\Block\Product\Context;
use Magento\Catalog\Helper\Image;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Gallery\ImagesConfigFactoryInterface;
use Magento\Catalog\Model\Product\Image\UrlBuilder;
use Magento\Framework\Data\Collection;
use Magento\Framework\DataObject;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Json\EncoderInterface;
use Magento\Framework\Stdlib\ArrayUtils;

/**
* Product gallery block
*
* @api
* @since 100.0.2
*/
class Gallery
{
/**
 * @var \Magento\Framework\Config\View
 */
protected $configView;

/**
 * @var EncoderInterface
 */
protected $jsonEncoder;

/**
 * @var array
 */
private $galleryImagesConfig;

/**
 * @var ImagesConfigFactoryInterface
 */
private $galleryImagesConfigFactory;

/**
 * @var UrlBuilder
 */
private $imageUrlBuilder;

/**
 * @param Context $context
 * @param ArrayUtils $arrayUtils
 * @param EncoderInterface $jsonEncoder
 * @param array $data
 * @param ImagesConfigFactoryInterface|null $imagesConfigFactory
 * @param array $galleryImagesConfig
 * @param UrlBuilder|null $urlBuilder
 */
public function __construct(
    Context $context,
    ArrayUtils $arrayUtils,
    EncoderInterface $jsonEncoder,
    array $data = [],
    ImagesConfigFactoryInterface $imagesConfigFactory = null,
    array $galleryImagesConfig = [],
    UrlBuilder $urlBuilder = null
) {
    //parent::__construct($context, $arrayUtils, $data);
    $this->jsonEncoder = $jsonEncoder;
    $this->galleryImagesConfigFactory = $imagesConfigFactory ?: ObjectManager::getInstance()
        ->get(ImagesConfigFactoryInterface::class);
    $this->galleryImagesConfig = $galleryImagesConfig;
    $this->imageUrlBuilder = $urlBuilder ?? ObjectManager::getInstance()->get(UrlBuilder::class);
}

/**
 * Retrieve collection of gallery images
 *
 * @return Collection
 */
public function getGalleryImages()
{
    $objectmanager = \Magento\Framework\App\ObjectManager::getInstance();
    $product = $objectmanager->create('Magento\Catalog\Model\Product');
    $images = $product->getMediaGalleryImages();
    if (!$images instanceof \Magento\Framework\Data\Collection) {
        return $images;
    }

    foreach ($images as $image) {
        $galleryImagesConfig = $this->getGalleryImagesConfig()->getItems();
        foreach ($galleryImagesConfig as $imageConfig) {
            $image->setData(
                $imageConfig->getData('data_object_key'),
                $this->imageUrlBuilder->getUrl($image->getFile(), $imageConfig['image_id'])
            );
        }
    }

    return $images;
}

/**
 * Retrieve product images in JSON format
 *
 * @return string
 */
public function afterGetGalleryImagesJson(\Magento\Catalog\Block\Product\View\Gallery $subject, $result)
{
    $objectmanager = \Magento\Framework\App\ObjectManager::getInstance();
    $product = $objectmanager->create('Magento\Catalog\Model\Product');
    $imagesItems = [];
    /** @var DataObject $image */
    foreach ($this->getGalleryImages() as $image) {
        $imageItem = new DataObject([
            'thumb' => $image->getData('small_image_url'),
            'img' => $image->getData('medium_image_url'),
            'full' => $image->getData('large_image_url'),
            'caption' => ($image->getLabel() ?: $this->getProduct()->getName()),
            //'caption' => ($image->getLabel() ?:''),
            'position' => $image->getData('position'),
            'isMain'   => $this->isMainImage($image),
            'type' => str_replace('external-', '', $image->getMediaType()),
            'videoUrl' => $image->getVideoUrl(),
        ]);

        foreach ($this->getGalleryImagesConfig()->getItems() as $imageConfig) {
            $imageItem->setData(
                $imageConfig->getData('json_object_key'),
                $image->getData($imageConfig->getData('data_object_key'))
            );
        }
        $imagesItems[] = $imageItem->toArray();
        //var_dump($image);
    }
    if (empty($imagesItems)) {
        $imagesItems[] = [
            'thumb' => $product->getDefaultPlaceholderUrl('thumbnail'),
            'img' => $product->getDefaultPlaceholderUrl('image'),
            'full' => $product->getDefaultPlaceholderUrl('image'),
            'caption' => '',
            'position' => '0',
            'isMain' => true,
            'type' => 'image',
            'videoUrl' => null,
        ];
        $result = json_encode($imagesItems);
    }
    return $result;;
}


/**
 * Is product main image
 *
 * @param \Magento\Framework\DataObject $image
 * @return bool
 */
public function isMainImage($image)
{
    $product = $this->getProduct();
    return $product->getImage() == $image->getFile();
}

/**
 * Returns image attribute
 *
 * @param string $imageId
 * @param string $attributeName
 * @param string $default
 * @return string
 */
public function getImageAttribute($imageId, $attributeName, $default = null)
{
    $attributes = $this->getConfigView()
        ->getMediaAttributes('Magento_Catalog', Image::MEDIA_TYPE_CONFIG_NODE, $imageId);
    return $attributes[$attributeName] ?? $default;
}


/**
 * Returns image gallery config object
 *
 * @return Collection
 */
private function getGalleryImagesConfig()
{
    if (false === $this->hasData('gallery_images_config')) {
        $galleryImageConfig = $this->galleryImagesConfigFactory->create($this->galleryImagesConfig);
        $this->setData('gallery_images_config', $galleryImageConfig);
    }

    return $this->getData('gallery_images_config');
}

}

I'm not getting up the expected result as this needs to display image and it's caption but image is not displaying. Can anyone suggest why it is not working from this method.

Thanks in advance.

0

You are using wrong syntax for plugin."preference" tag is used to override the file. Use this syntax to implement plugin.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
  <type name="Magento\Catalog\Block\Product\View\Gallery">
        <plugin name="plugin_test" type="Custom\Catalog\Plugin\Catalog\Block\Product\View" sortOrder="1"/>
 </type>
</config>
  • Thanks for the reply yeah that was my type. I've updated now and I've already tested by using preference but not working so tried by plugins which is also not working. – Suman Maharjan Aug 26 at 1:36
0

Can you please follow my code.

Create file: app/code/Dckap/Cnet/etc/di.xml

<?xml version="1.0"?> 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Block\Product\View\Gallery">
    <plugin name="Dckap_Cnet_Plugin_Magento_Catalog_Block_Product_View_Gallery" sortOrder="10" type="Dckap\Cnet\Plugin\Magento\Catalog\Block\Product\View\Gallery"/>
    </type>
</config>

Create file: app/code/Dckap/Cnet/Plugin/Magento/Catalog/Block/Product/View/Gallery.php

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * Product description block
 *
 * @author     Magento Core Team <core@magentocommerce.com>
 */
namespace Dckap\Cnet\Plugin\Magento\Catalog\Block\Product\View;
use Magento\Catalog\Helper\Image;
use Dckap\Cnet\Helper\Data;
/**
 * @api
 * @since 100.0.2
 */
class Gallery
{

    public function __construct(Image $imageHelper, Data $dataHelper)
    {        
        $this->_imageHelper = $imageHelper;
        $this->_dataHelper = $dataHelper;
    }

    public function getCNETResponse($cpn)
    {
        $headers = array(
        'Accept: application/json',
        'Content-Type: application/json',
        );
        $ch = curl_init();
        $cpn = preg_replace('/\s+/', '', $cpn);
        $subscriber_key = $this->_dataHelper->getGeneralConfig('subscriber_key');
        $zone_id = $this->_dataHelper->getGeneralConfig('zone_id');
        curl_setopt($ch, CURLOPT_URL, 'http://ws.cnetcontent.com/'.$subscriber_key.'/api/'.$zone_id.'?cpn='.$cpn);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        $result = json_decode($result, true);
        $data = '';
        if (isset($result['data']['ccs-gallery'])) {
            $data = $result['data']['ccs-gallery']['images'];        
        }        
        curl_close ($ch);
        return $data;
    }
    public function afterGetGalleryImagesJson(
        \Magento\Catalog\Block\Product\View\Gallery $subject,
        $result
    ) {        
        $imagesItems = [];
        //$this->imageHelper->getDefaultPlaceholderUrl('thumbnail');
        //print_r($subject->getProduct()->getSKU());die;
        $om = \Magento\Framework\App\ObjectManager::getInstance();
        $registry = $om->get('Magento\Framework\Registry');
        $product = $registry->registry('product'); 
        $images = $this->getCNETResponse($product->getSKU());
        if (!empty($images)) {
            foreach ($images as  $key => $image) {
                $imagesItems[] = [
                    'thumb' => $image['p75'],
                    'img' => $image['full'],
                    'full' => $image['full'],
                    'caption' => $product->getName(),
                    'position' => $key,
                    'isMain' => '',
                    'type' => 'image',
                    'videoUrl' => '',
                ];
            }
        } 
        if (empty($imagesItems)) {
            $imagesItems[] = [
                'thumb' => $this->_imageHelper->getDefaultPlaceholderUrl('thumbnail'),
                'img' => $this->_imageHelper->getDefaultPlaceholderUrl('image'),
                'full' => $this->_imageHelper->getDefaultPlaceholderUrl('image'),
                'caption' => '',
                'position' => '0',
                'isMain' => true,
                'type' => 'image',
                'videoUrl' => null,
            ];
        }
        return json_encode($imagesItems);
    }
}

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.