Come visualizzare i campioni sulla homepage Magento 2


8

Ho due cursori di prodotti

(basato su \Magento\Catalog\Block\Product\Widget\NewWidget) sulla mia homepage.

Vorrei aggiungere campioni a questi cursori del prodotto.

I cursori vengono aggiunti nel mio layout homepage.xml come di seguito:

<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>

Ho provato ad aggiungere i campioni aggiungendo il blocco con classe Magento\Swatches\Block\Product\Renderer\Listing\Configurablema questo non funziona come previsto.

Qualcuno sa come raggiungere questo obiettivo nella homepage?

Grazie.


Vuoi campioni nel prodotto nella homepage?
Rakesh Jesadiya,

No, voglio mostrare i campioni in una raccolta di prodotti. Ad esempio, nel tema Luma hai questa panoramica: dropbox.com/s/yxnwvzobmttkcq3/… . Come potrei aggiungere campioni?
user1393817

Puoi creare un blocco. Inserisci il Widget in quello e scegli Tipo di Widget: Catalogo Elenco prodotti e condizioni Seleziona i tuoi prodotti.
Ankit Shah,

@utente1393817, controlla la risposta di seguito per ottenere i campioni nella raccolta prodotti.
Rakesh Jesadiya,

@ user1393817, per favore fatemi sapere se avete problemi nel codice sottostante
Rakesh Jesadiya

Risposte:


10

Crea un semplice modulo per visualizzare i campioni nel prodotto configurabile nella homepage.

Per ottenere i campioni nella raccolta prodotti della home page, devi seguire i passaggi seguenti,

app / code / Test / Homeslider / registration.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; ?>

creare file xml da visualizzare nella homepage, app / codice / test / homeslider / vista / 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>

Crea file Block , app / codice / Test / Homeslider / Block / 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();
    }
}

Esegui comando,

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

Questo codice funziona bene @Rakesh. Grazie per quello Ma quando uso il file phtml usando il blocco statico, i campioni non vengono visualizzati. Qualche soluzione per quello?
Payal Patel,

@PayalPatel, devo cercare quello, non ho ancora verificato quel caso.
Rakesh Jesadiya,

@RakeshJesadiya, Funziona benissimo sulla homepage. Potete per favore aiutarmi ad aggiungere campioni sui prodotti correlati nella pagina del prodotto in Magento 2.3? In realtà, ho aggiunto degli swtach sui prodotti correlati, ma quando seleziono un campione, l'immagine del prodotto non cambia.
Vinod Kumar,

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.