6

Magento 2 Configurable Swatch option option not showing my custom theme but it's working in Default theme

My Default theme enter image description here

Custom Theme enter image description here

Product Details page it's working fine only problem is listing page. How to i fix this? What mistake i made here

<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
use Magento\Framework\App\Action\Action;

// @codingStandardsIgnoreFile

?>
<?php
/**
 * Product list template
 *
 * @var $block \Magento\Catalog\Block\Product\ListProduct
 */
?>

<?php
$_productCollection = $block->getLoadedProductCollection();
$_helper = $this->helper('Magento\Catalog\Helper\Output');
?>
<?php if (!$_productCollection->count()): ?>
    <div class="message info empty"><div><?php /* @escapeNotVerified */ echo __('We can\'t find products matching the selection.') ?></div></div>
<?php else: ?>
    <?php echo $block->getToolbarHtml() ?>
    <?php echo $block->getAdditionalHtml() ?>
    <?php
    if ($block->getMode() == 'grid') {
        $viewMode = 'grid';
        $image = 'category_page_grid';
        $showDescription = false;
        $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
    } else {
        $viewMode = 'list';
        $image = 'category_page_list';
        $showDescription = true;
        $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::FULL_VIEW;
    }
    /**
     * Position for actions regarding image size changing in vde if needed
     */
    $pos = $block->getPositioned();
    ?>
    <?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
      $current_category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');
      $parent_category = $current_category->getParentCategory();
      $Category_Name =  $current_category->getName();
      //echo $parent_category->getName(); ?>
      <h4 class="groceries-txt"><?php echo $Category_Name;?></h4>
    <div class="category-section products wrapper <?php /* @escapeNotVerified */ echo $viewMode; ?> products-<?php /* @escapeNotVerified */ echo $viewMode; ?>">
        <?php $iterator = 1; ?>
        <!-- <ol class="products list items product-items"> -->
            <?php /** @var $_product \Magento\Catalog\Model\Product */ ?>
            <?php foreach ($_productCollection as $_product): ?>
                <?php /* @escapeNotVerified */ echo($iterator++ == 1) ? '<div class="col-xs-6 col-sm-4 col-lg-3 col-block ">' : '</div><div class="col-xs-6 col-sm-4 col-lg-3 col-block">' ?>
                <div class="product-item-info category-cnt sub-category mtc-height " data-container="product-grid" style="height: 394px;">
                    <?php
                    $productImage = $block->getImage($_product, $image);
                    if ($pos != null) {
                        $position = ' style="left:' . $productImage->getWidth() . 'px;'
                            . 'top:' . $productImage->getHeight() . 'px;"';
                    }
                    ?>
                    <?php // Product Image ?>
                    <a href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>" class="product photo product-item-photo" tabindex="-1">
                        <?php //echo $productImage->toHtml(); ?>
                        <?php
                            //$image = 'category_page_grid' or 'category_page_list';
                            $_imagehelper = $this->helper('Magento\Catalog\Helper\Image');

                            $productImage = $_imagehelper->init($_product, $image)->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize(100)->getUrl();
                        ?>
                        <figure>
                            <img src="<?php echo $productImage; ?>" class="img-responsive" alt="<?php echo $_product->getName()?>" />
                        </figure>

                    </a>
                    <div class="product details product-item-details">
                        <?php
                            $_productNameStripped = $block->stripTags($_product->getName(), null, true);
                            $specialprice = $_product->getSpecialPrice();
                            $specialPriceFromDate = $_product->getSpecialFromDate();
                            $specialPriceToDate = $_product->getSpecialToDate();
                        ?>
                        <?php if($specialprice){?>
                        <div class="offer-lable">
                        <?php
                            $today = time();
                            $price = $_product->getPrice();
                            if($price){
                                $sale = round((($price-$specialprice)/$price)*100);
                            }
                            if ($specialprice) {
                                if ($today >= strtotime($specialPriceFromDate) && $today <= strtotime($specialPriceToDate) || $today >= strtotime($specialPriceFromDate) && is_null($specialPriceToDate)) { ?>
                                    <div class="label-product label-sale">
                                        <span class="sale-product-icon">
                                            <?php if($sale) { echo $sale.'% Off'; } else {echo __('Sale');} ?>
                                        </span>
                                    </div>
                                <?php }
                            }
                        ?>
                        </div>
                        <?php }?>
                        <?php /* @escapeNotVerified */ echo $block->getProductPrice($_product) ?>

                            <a class="product-item-link"
                               href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>" title="<?php echo $_helper->productAttribute($_product, $_product->getName(), 'name');?>">
                               <h5>
                                <?php //echo $_helper->productAttribute($_product, $_product->getName(), 'name'); ?>
                                <?php
                                    $prod_name = $_helper->productAttribute($_product, $_product->getName(), 'name');
                                   $count_str = strlen($prod_name);
                                   if ($count_str < 30) {
                                       echo $prod_name;
                                   } else {
                                       $offset = 0;
                                       $length = 20;  
                                       $prod_name = html_entity_decode($prod_name);                    
                                       echo htmlentities(mb_substr($prod_name,0,$length,'utf-8')). "...";;                        
                                   }
                                   ?>

                                </h5>
                            </a>

                        <?php echo $block->getReviewsSummaryHtml($_product, $templateType); ?>

                        <?php echo $block->getProductDetailsHtml($_product); ?>


                        <div class="product-item-inner">
                            <div class="product actions product-item-actions"<?php echo strpos($pos, $viewMode . '-actions') ? $position : ''; ?>>
                                <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 btn-cart">
                                                <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 data-role="add-to-links" class="actions-secondary"<?php echo strpos($pos, $viewMode . '-secondary') ? $position : ''; ?>>
                                    <?php if ($addToBlock = $block->getChildBlock('addto')): ?>
                                        <?php echo $addToBlock->setProduct($_product)->getChildHtml(); ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php if ($showDescription):?>
                                <div class="product description product-item-description">
                                    <?php /* @escapeNotVerified */ echo $_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description') ?>
                                    <a href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>" title="<?php /* @escapeNotVerified */ echo $_productNameStripped ?>"
                                       class="action more"><?php /* @escapeNotVerified */ echo __('Learn More') ?></a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php echo($iterator == count($_productCollection)+1) ? '</div>' : '' ?>
            <?php endforeach; ?>
        <!-- </ol> -->
    </div>
    <?php echo $block->getToolbarHtml() ?>
    <?php /*if (!$block->isRedirectToCartEnabled()) : ?>
        <script type="text/x-magento-init">
        {
            "[data-role=tocart-form], .form.map.checkout": {
                "catalogAddToCart": {}
            }
        }
        </script>
    <?php endif; */?>
<?php endif; ?>

How i will fix this?

14
  • Did u verify if there is no js conflicts? If you are using any jquery then you need to mention jQuery.noConflict() from this link: stackoverflow.com/questions/26991404/…
    – Sushivam
    Commented May 23, 2017 at 6:29
  • No Js conflict i checked
    – Magento 2
    Commented May 23, 2017 at 8:48
  • I think you should post a bit of your template code: layout and template involved in category view, maybe you are missing some block. Another thing I assume your template inherits from luma or blank right?
    – Marc Pont
    Commented May 23, 2017 at 11:35
  • i am using <parent>Magento/blank</parent>
    – Magento 2
    Commented May 23, 2017 at 13:50
  • which theme have you used? Please share your list.phtml file code to debug your issue. Commented May 24, 2017 at 9:40

1 Answer 1

6
+25

Step 1.First of all Edit your custom listing layout file

Vender/Module/view/frontend/layout/custom_listing.xml

    <referenceContainer name="main">
        <block class="CutomBlockClass"  name="cutome.block.name" before="-" cacheable="false" template = "custom.phtml">
            <block class="Magento\Framework\View\Element\RendererList" name="category.product.type.details.renderers.custom" as="details.renderers">
                <block class="Magento\Framework\View\Element\Template" as="default"/>
            </block>
        </block>
    </referenceContainer> 
    <referenceBlock name="category.product.type.details.renderers.custom">
        <block class="Magento\Swatches\Block\Product\Renderer\Listing\Configurable" as="configurable" template="custom/category/product/cutomeSwetchFile.phtml" >
            <arguments>
                <argument name="type" xsi:type="string">category-custom</argument>
            </arguments>
        </block>
    </referenceBlock>

Note: block name of category.product.type.details.renderers.custom and <referenceBlock name="category.product.type.details.renderers.custom"> should be same.

Step: 2 add css file in your custom layout file:

<css src="Magento_Swatches::css/swatches.css"/>

Step:3 Vender/Module/view/frontend/templates/custom/category/product/cutomeSwetchFile.phtml

<?php /** @var $block \Magento\Swatches\Block\Product\Renderer\Configurable */ ?>
<div class="swatch-opt-<?php echo $block->getType(); ?><?php /* @escapeNotVerified */ echo $block->getProduct()->getId() ?>"></div>
<script>
    require(["jquery", "jquery/ui", "Magento_Swatches/js/swatch-renderer"], function ($) {
        $('.swatch-opt-<?php echo $block->getType(); ?><?php /* @escapeNotVerified */ echo $block->getProduct()->getId() ?>').SwatchRenderer({
            selectorProduct: '.product-item-details',
            onlySwatches: true,
            enableControlLabel: false,
            numberToShow: <?php /* @escapeNotVerified */ echo $block->getNumberSwatchesPerProduct(); ?>,
            jsonConfig: <?php /* @escapeNotVerified */ echo $block->getJsonConfig(); ?>,
            jsonSwatchConfig: <?php /* @escapeNotVerified */ echo $block->getJsonSwatchConfig(); ?>,
            mediaCallback: '<?php /* @escapeNotVerified */ echo $block->getMediaCallback() ?>'
        });
    });
</script>
1
  • Can you post your complete code for this feature? Commented Oct 27, 2020 at 20:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.