1

How can I get the Products that are already added in the compare list Product Collection. For Visitor and as well as Login Customer. Can anyone guide me to solutions.

3 Answers 3

2
public function __construct(
    \Magento\Catalog\CustomerData\CompareProducts $compareProducts
) {
    $this->compareProducts = $compareProducts;
}

/*
    * Get current compare product list
    */
public function getCompareList(){
    return $this->compareProducts->getSectionData();
}

in phtml file,

<?php
    $compareObject = $block->getCompareList();
 ?>
<div class="compare-items">
<?php foreach($compareObject['items'] as $comparelist){                        
 ?>
    <div class="compProd">
        <a class="closeComp" data-href="<?php echo $block->getBaseUrl() ?>ajaxcompare/compare/remove/" data-compare="<?php echo $comparelist['id']; ?>">x</a>
        <span class="gBold cmPrd"><?php echo $comparelist['name']; ?></span>
    </div>
<?php } ?>
</div>
10
  • Will the collection works or both loggin and guest customer.?? May 7, 2018 at 12:53
  • Yes works for both. May 7, 2018 at 12:59
  • Can I use the above code in controller Will it works? @Rakesh Jesadiya May 7, 2018 at 13:11
  • Yes you can use in controller also and its works May 7, 2018 at 13:28
  • 1
    @BalwantSingh. Use this code in controller. In my case, I need compare products count in every page. I use ajax and get the count as well as compare product list. Aug 15, 2020 at 7:16
0

Inject the following class in the constructor where you want to use it.

\Magento\Catalog\Model\Product\Compare\ListCompare

public function __construct(
....
....
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\Product\Compare\ListCompare $listCompare,
array $data = []
....
) {
...
parent::__construct($context, $data);
$this->listCompare = $listCompare;
...
}

2) For getting collection :-

$this->listCompare->getItemCollection();
12
  • Like if i HAVE ADDED 3 PRODUCT's Already into list then, will i get the count.Here. May 7, 2018 at 12:50
  • Yes. You can count here. May 7, 2018 at 13:29
  • When I use your code in my controller i am getting below error as screen shot prnt.sc/jfkw3r @Rohan Hapani May 9, 2018 at 6:07
  • You can use this code where you want to get collection. May 9, 2018 at 6:11
  • Check my updated answer and use this code. May 9, 2018 at 6:14
0

Controller

<?php

namespace Vendor\Module\Controller\Compare;

class Count extends \Magento\Framework\App\Action\Action
{
     /**
     * @var \Magento\Catalog\CustomerData\CompareProducts
     */
    private $_compareProducts;

    /**
     * @var \Magento\Framework\Json\Helper\Data
     */
    protected $jsonHelper;

     /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Catalog\CustomerData\CompareProducts $productCompare
     * @param \Magento\Framework\Json\Helper\Data $jsonHelper
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Catalog\CustomerData\CompareProducts $compareProducts,
        \Magento\Framework\Json\Helper\Data $jsonHelper,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->_compareProducts = $compareProducts;
        $this->jsonHelper = $jsonHelper;
    }

    /**
     * Check if any item in compare list
     *
     * @return \Magento\Framework\Controller\Result\Redirect
     */
    public function execute()
    {
        $params = $this->getRequest()->getParams();
        $checkCompare = $params['checkCompare'];
        $isCompare = 0;
        if($checkCompare) {

         /**
          * print_r($this->_compareProducts->getSectionData());
          * You will get all info of compare product
          * I just need count so I have used that only
          */
            
            $isCompare = $this->_compareProducts->getSectionData()['count'];
        }
        return $this->getResponse()->representJson(
            $this->jsonHelper->jsonEncode($isCompare)
        );
    }
}

compare.phtml file

<?php
$helper = $this->helper('Vendor\Module\Helper\Data');
$isLoggedIn = 0;
if($helper->isLoggedIn()) {
    $isLoggedIn = 1;
}

?>
<script type="text/javascript">
    require([
    'jquery',
    'jquery/ui'
    ], function ($) {
        jQuery(document).ready( function() {
            // if any customer is logged in then check compare item count
            var isLoggedIn = '<?php echo $isLoggedIn; ?>';
            isLoggedIn = parseInt(isLoggedIn);
            if(isLoggedIn) {
                jQuery.ajax({
                    type: 'POST',
                    url: "<?php echo $block->getUrl('frontend_route/controller_name/class_name'); ?>",
                    data : {
                        checkCompare: 1,
                    },
                    dataType: 'json',
                    success: function (data) {
                        if(data > 0) {
                            $(".compare-signal").show();
                        } else {
                            $(".compare-signal").hide();
                        }
                    }
                });
            } else {
                $(".compare-signal").hide();
            }
        });
    });
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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