Cara menampilkan swatch di beranda Magento 2


8

Saya punya dua produk slider

(berdasarkan \Magento\Catalog\Block\Product\Widget\NewWidget) di beranda saya.

Saya ingin menambahkan swatch ke slider produk ini.

Slider ditambahkan di tata letak homepage.xml saya seperti di bawah ini:

<container name="items.wrapper.slider" after="full.width.white.bar" htmlTag="div"
           htmlClass="wrapper wrapper--large c-catalog__products--slider-wrapper">
    <block class="Silvan\TestExtension\Block\Product\Widget\NewWidget"
           template="Magento_Catalog::product/widget/new/content/new_grid.phtml" name="new.products">
        <block class="Magento\Swatches\Block\Product\Renderer\Listing\Configurable" as="new.products.swatches" template="Magento_Swatches::product/listing/renderer.phtml" />
    </block>
</container>

Saya sudah mencoba menambahkan swatch dengan menambahkan blok dengan kelas Magento\Swatches\Block\Product\Renderer\Listing\Configurabletetapi ini tidak berfungsi seperti yang diharapkan.

Adakah yang tahu cara mencapai ini di beranda?

Terima kasih.


Apakah Anda ingin carikan di produk di beranda?
Rakesh Jesadiya

Tidak, saya ingin menunjukkan swatch dalam koleksi produk. Misalnya, dalam tema Luma Anda memiliki gambaran umum ini: dropbox.com/s/yxnwvzobmttkcq3/… . Bagaimana saya bisa menambahkan carikan?
user1393817

Anda dapat Membuat Blokir. Masukkan Widget di & Pilih Jenis Widget: Katalog Daftar Produk & Dalam Kondisi pilih produk Anda.
Ankit Shah

@ user1393817 silakan periksa jawaban di bawah ini untuk mendapatkan sampel dalam koleksi produk.
Rakesh Jesadiya

@ user1393817, tolong beri tahu saya jika Anda memiliki masalah dalam kode di bawah ini
Rakesh Jesadiya

Jawaban:


10

Buat modul sederhana untuk carikan tampilan pada produk yang dapat dikonfigurasi di beranda.

Anda harus mengikuti langkah-langkah di bawah ini untuk mendapatkan contoh pada koleksi produk beranda,

app / code / Test / Homeslider / registrasi.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Test_Homeslider',
    __DIR__
);

app / code / Test / Homeslider / etc / module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Test_Homeslider" setup_version="1.0.0" schema_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>

app / code / Test / Homeslider / view / frontend / templates / products.phtml

<?php
use Magento\Framework\App\Action\Action;

$productCollection = $this->getProductCollection();
$imageBlock =  $block->getLayout()->createBlock('Magento\Catalog\Block\Product\ListProduct');
$showCart = true;
$type = 'widget-new-grid';
$viewMode = 'grid'; 
$image = 'category_page_grid';
$pos = $block->getPositioned();
?>
<div class="title">
    <strong class="newproduct">New Product</strong>
</div>

<div class="products-grid">
    <div id="topseller-slider" class="products list items product-items owlslider" data-jcarousel="true">
        <ul class="product-items" id="topsellerowlslider">
            <?php $iterator = 1; ?>
            <?php foreach ($productCollection as $_product): ?>
            <?php $productImage = $imageBlock->getImage($_product, 'category_page_grid'); 
                if ($pos == null) {                                                        
                    $position = ' style="left:' . $productImage->getWidth() . 'px;'
                        . 'top:' . $productImage->getHeight() . 'px;"';
                }
                ?>
            <?php /* @escapeNotVerified */ echo($iterator++ == 1) ? '<li class="product-item"><div class="product-item-info">' : '</div></li><li class="product-item"><div class="product-item-info">' ?>
            <a href="<?php echo $_product->getProductUrl(); ?>"><?php echo $productImage->toHtml()  ?></a>
            <div class="product details product-item-details">
                <strong class="product name product-item-name">
                <a class="product-item-link"  href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>">
                <?php /* @escapeNotVerified */ echo $_product->getName(); ?>
                </a>
                </strong>
                <?php if ($showCart): ?>
                <?php echo $this->getProductPricetoHtml($_product, $type); ?>
                <?php echo $block->getProductDetailsHtml($_product); ?>
                <div class="product-item-inner">
                    <div class="product actions product-item-actions">
                        <div class="actions-primary"<?php echo strpos($pos, $viewMode . '-primary') ? $position : ''; ?>>
                            <?php if ($_product->isSaleable()): ?>
                            <?php $postParams = $block->getAddToCartPostParams($_product); ?>
                            <form data-role="tocart-form" action="<?php /* @escapeNotVerified */ echo $postParams['action']; ?>" method="post">
                                <input type="hidden" name="product" value="<?php /* @escapeNotVerified */ echo $postParams['data']['product']; ?>">
                                <input type="hidden" name="<?php /* @escapeNotVerified */ echo Action::PARAM_NAME_URL_ENCODED; ?>" value="<?php /* @escapeNotVerified */ echo $postParams['data'][Action::PARAM_NAME_URL_ENCODED]; ?>">
                                <?php echo $block->getBlockHtml('formkey')?>
                                <button type="submit"
                                    title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>"
                                    class="action tocart primary">
                                <span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
                                </button>
                            </form>
                            <?php else: ?>
                            <?php if ($_product->getIsSalable()): ?>
                            <div class="stock available"><span><?php /* @escapeNotVerified */ echo __('In stock') ?></span></div>
                            <?php else: ?>
                            <div class="stock unavailable"><span><?php /* @escapeNotVerified */ echo __('Out of stock') ?></span></div>
                            <?php endif; ?>
                            <?php endif; ?>
                        </div>

                        <div class="actions-secondary" data-role="add-to-links">
                            <?php if ($this->helper('Magento\Wishlist\Helper\Data')->isAllow()): ?>
                                <a href="#"
                                   data-post='<?php /* @escapeNotVerified */ echo $block->getAddToWishlistParams($_product); ?>'
                                   class="action towishlist" data-action="add-to-wishlist"
                                   title="<?php /* @escapeNotVerified */ echo __('Add to Wish List') ?>">
                                    <span><?php /* @escapeNotVerified */ echo __('Add to Wish List') ?></span>
                                </a>
                            <?php endif; ?>
                            <?php if ($block->getAddToCompareUrl()) ?>
                                <?php $compareHelper = $this->helper('Magento\Catalog\Helper\Product\Compare');?>
                                <a href="#" class="action tocompare"
                                   data-post='<?php /* @escapeNotVerified */ echo $compareHelper->getPostDataParams($_product);?>'
                                   title="<?php /* @escapeNotVerified */ echo __('Add to Compare') ?>">
                                    <span><?php /* @escapeNotVerified */ echo __('Add to Compare') ?></span>
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php echo($iterator == count($productCollection)+1) ? '</div></li>' : '' ?>
            <?php endforeach ?>
        </ul>
    </div>
</div>
</div>
<?php if (!$block->isRedirectToCartEnabled()) : ?>
<script type="text/x-magento-init">
    {
        "[data-role=tocart-form], .form.map.checkout": {
            "catalogAddToCart": {}
        }
    }
</script>
<?php endif; ?>

buat file xml untuk tampilan di dalam beranda, aplikasi / kode / Tes / Homeslider / view / frontend / layout / cms_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
      <head>
           <css src="Magento_Swatches::css/swatches.css"/>
    </head> 
    <body>
        <referenceBlock name="homepage.swatchrenderer">
                <block class="Magento\Swatches\Block\Product\Renderer\Listing\Configurable" as="configurable" template="Magento_Swatches::product/listing/renderer.phtml" />
        </referenceBlock>     

        <referenceContainer name="main">
          <container name="topproduct" htmlTag="div" htmlClass="topproduct">
                  <block class="Test\Homeslider\Block\Productslist" name="productlist" template="Test_Homeslider::products.phtml">
                      <block class="Magento\Framework\View\Element\RendererList" name="homepage.swatchrenderer" as="homepage.toprenderers">
                        <block class="Magento\Framework\View\Element\Template" as="default"/>
                      </block>
                  </block>
           </container>
        </referenceContainer>
    </body>
</page>

Buat file Blokir , aplikasi / kode / Tes / Homeslider / Blok / Productslist.php

<?php
namespace Test\Homeslider\Block;
use Magento\Catalog\Block\Product\ListProduct;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\Product;

class Productslist extends \Magento\Framework\View\Element\Template
{   
    protected $_productCollectionFactory;    

    public function __construct(      
        \Magento\Framework\View\Element\Template\Context $context,    
        \Magento\Catalog\Block\Product\Context $gridcontext,  
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,       
        \Magento\Catalog\Block\Product\ListProduct $listProductBlock,

        array $data = []
    )
    {   
        $this->_productCollectionFactory = $productCollectionFactory; 
        $this->listProductBlock = $listProductBlock;
        $this->reviewRenderer = $gridcontext->getReviewRenderer();     
        $this->_compareProduct = $gridcontext->getCompareProduct();
        $this->_wishlistHelper = $gridcontext->getWishlistHelper();     
        parent::__construct($context, $data);
    }

    public function isRedirectToCartEnabled()
    {
        return $this->_scopeConfig->getValue(
            'checkout/cart/redirect_to_cart',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    public function getProductDetailsHtml(\Magento\Catalog\Model\Product $product)
    {
        $renderer = $this->getDetailsRenderer($product->getTypeId());
        if ($renderer) {
            $renderer->setProduct($product);
            return $renderer->toHtml();
        }
        return '';
    }

    public function getDetailsRenderer($type = null)
    {
        if ($type === null) {
            $type = 'default';
        }
        $rendererList = $this->getDetailsRendererList();
        if ($rendererList) {
            return $rendererList->getRenderer($type, 'default');
        }
        return null;
    }

    protected function getDetailsRendererList()
    {
        return $this->getDetailsRendererListName() ? $this->getLayout()->getBlock(
            $this->getDetailsRendererListName()
        ) : $this->getChildBlock(
            'homepage.toprenderers'
        );
    }
    public function getProductPricetoHtml(
        \Magento\Catalog\Model\Product $product,
        $priceType = null
    ) {
        $priceRender = $this->getLayout()->getBlock('product.price.render.default');
        $price = '';
        if ($priceRender) {
            $price = $priceRender->render(
                \Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE,
                $product
            );
        }
        return $price;
    }
    public function getProductCollection()
    {        
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToFilter('type_id', 'configurable');
        $collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
        $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
        $collection->setPageSize(10); 
        $collection->addAttributeToSelect('*');
        return $collection;
    }

    public function getAddToCartPostParams($product)
    {
        return $this->listProductBlock->getAddToCartPostParams($product);
    }

    public function getAddToWishlistParams($product)
    {
        return $this->_wishlistHelper->getAddParams($product);
    }
    public function getAddToCompareUrl()
    {
        return $this->_compareProduct->getAddUrl();
    }
}

Jalankan perintah,

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy

Kode ini berfungsi dengan baik @Rakesh. Terima kasih untuk itu. Tetapi ketika saya menggunakan file phtml menggunakan blok statis, swatch tidak ditampilkan. Ada solusi untuk itu?
Payal Patel

@PayalPatel, saya harus mencarinya, saya belum memeriksa kopernya.
Rakesh Jesadiya

@RakeshJesadiya, Ini berfungsi dengan baik di beranda. Bisakah Anda membantu saya menambahkan carikan pada produk terkait di halaman produk di Magento 2.3? Sebenarnya, saya telah menambahkan swtaches pada produk terkait tetapi ketika saya memilih swatch apapun maka gambar produk tidak berubah.
Vinod Kumar

Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.