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.

0
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>
  • Will the collection works or both loggin and guest customer.?? – Learing_Coder May 7 '18 at 12:53
  • Yes works for both. – Rakesh Jesadiya May 7 '18 at 12:59
  • Can I use the above code in controller Will it works? @Rakesh Jesadiya – Learing_Coder May 7 '18 at 13:11
  • Yes you can use in controller also and its works – Rakesh Jesadiya May 7 '18 at 13:28
  • Hello @Rakesh I am getting the error when add above code in my controller to fetch collection of compare list as below prnt.sc/jfnw1c – Learing_Coder May 9 '18 at 11:54
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();
  • Like if i HAVE ADDED 3 PRODUCT's Already into list then, will i get the count.Here. – Learing_Coder May 7 '18 at 12:50
  • Yes. You can count here. – Rohan Hapani May 7 '18 at 13:29
  • When I use your code in my controller i am getting below error as screen shot prnt.sc/jfkw3r @Rohan Hapani – Learing_Coder May 9 '18 at 6:07
  • You can use this code where you want to get collection. – Rohan Hapani May 9 '18 at 6:11
  • Check my updated answer and use this code. – Rohan Hapani May 9 '18 at 6:14

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.