{Hello} Buddies, on this weblog, we’ll learn the way can we add further or customized content material or media to Configurable Merchandise’ Fotorama media gallery on the entrance finish in visible and textual content swatches case.
For dropdown swatch kind, examine our weblog Add Customized Content material in Configurable Product Media Gallery – Magento 2
In Magento 2, on the configurable product web page, for rendering the swatch attributes, <magento-root-dir.>/vendor/magento/module-swatches/view/base/net/js/swatch-renderer.js file is accountable.
So, so as to add further content material within the configurable product’s media gallery(in textual content and visible swatch case), we have to override just a few strategies of the swatch-renderer js file.
For instance, updateBaseImage, _onGalleryLoaded and _loadMedia features are accountable for updating the media gallery after swatch rendering and swatch choice.
So, so as to add the customized content material I’ve overridden the required features and added some required recordsdata that are required to attain our purpose.
Initially, we’ll create a demo module. Right here, I’ve created the Webkul_ExtraContentInFotorama module. Additional, observe the under steps:
1. Create a di.xml file contained in the <magento-root-dir>/app/code/Webkul/ExtraContentInFotorama/and so forth/ listing.
<?xml model="1.0"?> <!-- /** * Webkul Software program. * * @class Webkul * @bundle Webkul_ExtraContentInFotorama * @creator Webkul Software program Personal Restricted * @copyright Webkul Software program Personal Restricted ( * @license */ --> <config xmlns:xsi=" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/and so forth/config.xsd"> <!--Add Additional Configuration Knowledge In JsonConfig--> <kind title="MagentoConfigurableProductBlockProductViewTypeConfigurable"> <plugin title="Wk_afterGetJsonConfig" kind="WebkulExtraContentInFotoramaPluginConfigurableProductBlockConfigurableAfterGetJsonConfigPlugin" sortOrder="50" /> </kind> </config>
2. Create ConfigurableAfterGetJsonConfigPlugin.php file contained in the <magento-root-dir>/app/code/Webkul/ExtraContentInFotorama/Plugin/ConfigurableProduct/Block/ listing.
<?php /** * Webkul Software program. * * @class Webkul * @bundle Webkul_ExtraContentInFotorama * @creator Webkul Software program Personal Restricted * @copyright Webkul Software program Personal Restricted ( * @license */ namespace WebkulExtraContentInFotoramaPluginConfigurableProductBlock; class ConfigurableAfterGetJsonConfigPlugin /** * @var MagentoFrameworkAppRequestInterface */ protected $request; /** * @var MagentoFrameworkJsonHelperData */ protected $jsonHelper; /** * Initialize dependencies * * @param MagentoFrameworkJsonHelperData $jsonHelper * @param MagentoFrameworkAppRequestInterface $request * @return void */ public perform __construct( MagentoFrameworkJsonHelperData $jsonHelper, MagentoFrameworkAppRequestInterface $request ) $this->request = $request; $this->jsonHelper = $jsonHelper; /** * Composes configuration for js * * @param MagentoConfigurableProductBlockProductViewTypeConfigurable $topic * @param string $resultJson * @return string */ public perform afterGetJsonConfig( MagentoConfigurableProductBlockProductViewTypeConfigurable $topic, $resultJson ) //Verify if request is produced from product web page// if (strtolower($this->request->getFullActionName()) == "catalog_product_view") $end result = $this->jsonHelper->jsonDecode($resultJson); /////Set Additional Configuration Knowledge///// $customConfig = []; $customConfig["linkUrl"] = " $customConfig["thumbnailImage"] = "Present a thumbnail Picture URL"; $customConfig["linkContent"] = "Design Patterns in Magento 2"; //set tremendous attribute id, on which choice you wish to change the content material// $customConfig["defaultVariantAttribute"] = 138; $end result["customConfig"] = $customConfig; $resultJson = $this->jsonHelper->jsonEncode($end result); ///////// return $resultJson;
3. Create a requires-config.js file to say the mixin file for the swatch-renderer.js file contained in the <magento-root-dir.>/app/code/Webkul/ExtraContentInFotorama/view/frontend/ listing.
/** * Webkul Software program. * * @class Webkul * @bundle Webkul_ExtraContentInFotorama * @creator Webkul Software program Personal Restricted * @copyright Webkul Software program Personal Restricted ( * @license */ var config = config: mixins: 'Magento_Swatches/js/swatch-renderer' : 'Webkul_ExtraContentInFotorama/js/swatch-renderer':true ;
4. Create a swatch-renderer.js file contained in the <magento-root-dir.>/app/code/Webkul/ExtraContentInFotorama/view/frontend/net/js/ listing.
/** * Webkul Software program. * * @class Webkul * @bundle Webkul_ExtraContentInFotorama * @creator Webkul Software program Personal Restricted * @copyright Webkul Software program Personal Restricted ( * @license */ outline([ 'jquery', 'underscore', 'mage/translate' ], perform ($, _, $t) { 'use strict'; return perform (SwatchRenderer) { $.widget('mage.SwatchRenderer', SwatchRenderer, { /** * Replace [gallery-placeholder] or [product-image-photo] * @param Array photos * @param jQuery context * @param Boolean isInProductView */ updateBaseImage: perform (photos, context, isInProductView) , /** * Callback which fired after gallery will get initialized. * * @param HTMLElement factor - DOM factor related to a gallery. */ _onGalleryLoaded: perform (factor) var galleryObject = factor.information('gallery'); //////////// var currImgs = galleryObject.returnCurrentImages(); //Load Additional Content material// this._loadExtraContent(); //Push Additional Content material in photos gallery var self = this.choices.jsonConfig.customConfig; var modelThumbnailImg = self.thumbnailImage; this._pushExtraContent(currImgs, modelThumbnailImg); ////////////////// this.choices.mediaGalleryInitial = currImgs; ///Replace Present Pictures in Media Gallery/// galleryObject.updateData(currImgs); , /** * Load media gallery utilizing ajax or json config. * * @non-public */ _loadMedia: perform () var self = this.choices.jsonConfig.customConfig; //Get Customized Config. var $foremost = this.inProductList ? this.factor.mother and father('.product-item-info') : this.factor.mother and father('.column.foremost'), photos; if (this.choices.useAjax) this._debouncedLoadProductMedia(); else photos = this.choices.jsonConfig.photos[this.getProduct()]; if (!photos) photos = this.choices.mediaGalleryInitial; ////////////Load Additional Content material///// this._loadExtraContent(); //Take away Additional Content material from picture array photos = this._removeExtraContentfromArray(photos); var self = this.choices.jsonConfig.customConfig; var modelThumbnailImg = self.thumbnailImage; //Push Additional Content material from picture array this._pushExtraContent(photos, modelThumbnailImg); ////////////////// this.updateBaseImage(this._sortImages(photos), $foremost, !this.inProductList); , /** * Delete Further Additional Content material from array * * @param Array imagesArray * @returns Array * @non-public */ _removeExtraContentfromArray: perform(imagesArray) imagesArray = imagesArray.filter(factor => factor.kind !== "ExtraContent"); return imagesArray; , /** * Push Additional Content material in array * * @param Array fotoramaContentArray * @param string modelThumbnailImg * @non-public */ _pushExtraContent: perform(fotoramaContentArray, modelThumbnailImg) , /** * Get Chosen Variant Worth * * @return string * @non-public */ _getSelectedVariantValue: perform() { var self = this.choices.jsonConfig.customConfig; var optionTextVal = ""; var optionTextArr = []; var selectedText = ""; var selectedVal = ""; var selectedSwatchAttrId = 0; var defaultVariantAttribute = self.defaultVariantAttribute; if ($('.product-options-wrapper choose[id^="attribute"]').discover().size) selectedText = $('.product-options-wrapper choose[id^="attribute"] possibility:chosen').textual content(); else { if ($('.swatch-attribute-options .swatch-option[aria-checked="true"]').size) var swatchId = ""; var idParts = []; $('.swatch-attribute-options .swatch-option[aria-checked="true"]').every(perform() swatchId = $(this).attr("id"); idParts = swatchId.break up('-'); for (let index=0; index<idParts.size; index++) if ($.isNumeric(idParts[index])) selectedSwatchAttrId = idParts[index]; break; if (parseInt(defaultVariantAttribute) == selectedSwatchAttrId) selectedText = $(this).attr("data-option-label"); ); } /////Get Chosen Variant Worth///// selectedVal = $('.product-options-wrapper choose[id^="attribute"] possibility:chosen').val(); if (selectedVal == "" && $('.product-options-wrapper choose[id^="attribute"]').discover().size) selectedText = $('.product-options-wrapper choose[id^="attribute"] possibility:eq(1)').textual content(); else selectedVal = selectedText; ///// if ($('.product-options-wrapper choose[id^="attribute"]').discover().size) if (selectedText.indexOf('+') == -1) optionTextVal = selectedText; else optionTextArr = selectedText.break up('+'); optionTextVal = $.trim(optionTextArr[0]); else optionTextVal = selectedVal; return optionTextVal; }, /** * Occasion for swatch choices * * @param Object $this * @param Object $widget * @non-public */ _OnClick: perform ($this, $widget) var self = this.choices.jsonConfig.customConfig; var wkExtraContentDiv = $("#wkExtraContent"); var mainVariantAttributeId = self.defaultVariantAttribute; var swatchId = $this.attr("id"); var idParts = swatchId.break up('-'); var selectedSwatchAttrId = 0; for (let index=0; index<idParts.size; index++) if ($.isNumeric(idParts[index])) selectedSwatchAttrId = idParts[index]; break; if (typeof wkExtraContentDiv == "object" && selectedSwatchAttrId == parseInt(mainVariantAttributeId)) var label = $this.attr("data-option-label"); var bgColor = "#86FA50"; swap (label) case 'Gold': bgColor = "#DFD906"; break; case 'Diamond': bgColor = "#AFF3F2"; break; setTimeout(perform() $("#wkExtraContent").css("background-color", bgColor); , 300); this._super($this, $widget); , /** * Load Additional Content material * * @non-public */ _loadExtraContent: perform() var thisJs = this; var self = this.choices.jsonConfig.customConfig; var divFotorama = $('div.gallery-placeholder > div.fotorama'); if (self.linkUrl == "") return; var variantText = "None"; //Get Chosen Variant Worth variantText = thisJs._getSelectedVariantValue(); divFotorama.on('fotorama:load', perform fotorama_onLoad(e, fotorama, further) if (further.body.kind === 'ExtraContent' && further.body.src != "") var extraContentHtml = ''; extraContentHtml += '<div id="wkExtraContent" model="background-color:#86FA50">'; extraContentHtml += '<h1 model="margin-top:250px">'+'Additional Content material'+'</h1>'; ///Present Variant Textual content/// if (variantText != '') extraContentHtml += '<p model="font-size:20px">Chosen Variant:</p>'; extraContentHtml += '<p model="font-size:18px">'+variantText+'</p><br/>'; ///////////////// extraContentHtml += '<a href="'+self.linkUrl+'" model="font-size:18px">' extraContentHtml += self.linkContent+'</a>'; extraContentHtml += '</div>'; further.body.$stageFrame.html(extraContentHtml); ); }); return $.mage.SwatchRenderer; }; });
5. After including the above code to your module. Deploy the code and see the end result within the textual content swatch case. Seek advice from the under photos for the end result.

6. See the end result within the visible swatch case. Seek advice from the under photos for the end result.


Be aware: Keep in mind so as to add <sequence> within the module.xml file to load the Magento_Swatches module earlier than your customized module.
You might also examine the Magento 2 Superior Media Supervisor extension to edit the photographs current within the media gallery and add watermarks, filter, rotate, resize, and extra.
#Magento #Customized #Content material #Configurable #Product #Media #Gallery