Magento 2: Display Swatchs in my template file
Domanda
I am fetching configuration products from SKU, I am displaying configuration by dropdown, and using selected value I am generating proper SKU of that product.
Ex: if customer select 'MH01' and select configure color:'Black' & Size:'S', the product's SKU will be 'MH01-S-Black' and it's working perfectly fine but now I want to replace configure dropdown by swatches. I am already getting the value of attributes for the swatch, but not successfully display to my template file.
Here is my controller:
$getProduct = $this->getRequest()->getParam('get_product');
$productDetail = $this->productRepository->get($getProduct);
$data['name'] = $productDetail->getName();
$data['id'] = $productDetail->getId();
$data['sku'] = $productDetail->getSku();
$data['price'] = $productDetail->getFinalPrice();
$data['stock'] = $productDetail->getQuantityAndStockStatus();
$data['config'] = $this->configurable->getConfigurableAttributesAsArray($productDetail);
$result = $this->jsonFactory->create();
$result->setData($data);
return $result;
as per my knowledge, $data['config'] have an all attribute value for swatches, please correct me if I am wrong.
Source: how to get swatches attribute option in magento 2
Data in $data['config']: https://drive.google.com/file/d/1vV1EwHqzjO1RZHkpQ6KGR19qb5jxgRVL/view?usp=sharing
My template viewproduct.phtml (writing only AJAX)
require(['jquery'],function(){
jQuery(document).ready(function() {
var data = '';
jQuery("#load_product").submit(function(e){
e.preventDefault();
var getProduct = jQuery("#get_product").val();
var url = "<?php echo $block->getUrl('viewproduct/loadproduct/index');?>";
jQuery.ajax({
url: url,
type: "POST",
data: {get_product:getProduct},
showLoader: true,
cache: false,
success: function(response) {
console.log(response);
data = response;
if (!jQuery.trim(response)) {
alert("Product is not configurable");
location.reload();
} else {
jQuery("#newProduct").html('');
jQuery("#example").css('visibility', 'visible');
jQuery('.productName').html('');
jQuery('.productName').html(response.name);
jQuery('.productPrice').html('');
jQuery('.productPrice').html(response.price+'$');
jQuery.each(response.config, function (index,value) {
var select = value.label + '<select class="configurable" name="' + index + '" >';
jQuery.each(value.values, function (key, opt) {
select += '<option value="' + opt.value_index + '">' + opt.label + '</option>>'
});
select += '</select>';
jQuery("#newProduct").append(select);
});
}
}
});
});
I also tried other answers to display swatches, but
- they are using objectManager.
- mostly answer showing swatches for category page or productList.
like:How to get visual swatch image from attribute_id?
I need swatches for specific products which users asking, I am getting data from AJAX request.
Any help, a suggestion would be appreciated
Nessuna soluzione corretta