I want to add custom code in gallery.phtml in the PDP section on my custom module. I tried this=> called default the block in catalog_product_view.xml
<referenceBlock name="product.info.media.image">
<action method="setTemplate">
<argument name="template" xsi:type="string">Ajith_Mymodule::product/view/gallery.phtml</argument>
</action>
</referenceBlock>
loaded gallery.phtml with and without default code, nothing works well for me. Am I'm trying the correct method or did anybody give me the idea to do this?
CodePudding user response:
This method is working properly
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Product media data template
*
* @var $block \Magento\Catalog\Block\Product\View\Gallery
*/
?>
<?php
$images = $block->getGalleryImages()->getItems();
$mainImage = current(array_filter($images, function ($img) use ($block) {
return $block->isMainImage($img);
}));
if (!empty($images) && empty($mainImage)) {
$mainImage = $block->getGalleryImages()->getFirstItem();
}
$helper = $block->getData('imageHelper');
$mainImageData = $mainImage ?
$mainImage->getData('medium_image_url') :
$helper->getDefaultPlaceholderUrl('image');
?>
<div data-gallery-role="gallery-placeholder">
<img
alt="main product photo"
src="<?= /* @noEscape */ $mainImageData ?>"
/>
</div>
<script type="text/x-magento-init">
{
"[data-gallery-role=gallery-placeholder]": {
"mage/gallery/gallery": {
"mixins":["magnifier/magnify"],
"magnifierOpts": <?= /* @noEscape */ $block->getMagnifier() ?>,
"data": <?= /* @noEscape */ $block->getGalleryImagesJson() ?>,
"options": <?= /* @noEscape */ $block->getGalleryOptions()->getOptionsJson() ?>,
"fullscreen": <?= /* @noEscape */ $block->getGalleryOptions()->getFSOptionsJson() ?>,
"breakpoints": <?= /* @noEscape */ $block->getBreakpoints() ?>
}
}
}
</script>
call this in our custom template
CodePudding user response:
If we take a look:
vendor/magento/module-product-video/Observer/ChangeTemplateObserver.php
We can see that this template will be added via Observer event. So, we need to disable this observer event in our module. And then, try to add our custom template.
Vendor/Module/etc/events.xml
<event name=""catalog_product_gallery_prepare_layout"">
<observer name=""change_template"" disabled=""true""/>
<observer name=""custom_change_template"" instance=""Vendor\Module\Observer\ChangeTemplateObserver"" />
</event>
Vendor/Module/Observer/ChangeTemplateObserver.php
<?php
namespace Vendor\Module\Observer;
use Magento\Framework\Event\ObserverInterface;
class ChangeTemplateObserver implements ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
{
$observer->getBlock()->setTemplate('Vendor_Module::helper/gallery.phtml');
}
}