As per my requirements, I have created this type of controller. So basically you need 2 types of Controller.
The first one for adding the product in the comparison list and second for removing the product from the comparison list.
Step 1. Please create one controller for Add Product as below.
<?php
namespace MagemonkeysCompareajaxControllerIndex;
use MagentoCatalogApiProductRepositoryInterface;
use MagentoFrameworkDataFormFormKeyValidator;
use MagentoFrameworkViewResultPageFactory;
use MagentoFrameworkControllerResultJsonFactory;
use MagentoFrameworkExceptionNoSuchEntityException;
use MagentoFrameworkEventManagerInterface as EventManager;
class AddCompare extends MagentoFrameworkAppActionAction
{
/**
* @var JsonFactory
*/
protected $resultJsonFactory;
/**
* @var EventManager
*/
private $eventManager;
/**
* Customer id
*
* @var null|int
*/
protected $_customerId = null;
/**
* Catalog session
*
* @var MagentoCatalogModelSession
*/
protected $_catalogSession;
/**
* Catalog product compare list
*
* @var MagentoCatalogModelProductCompareListCompare
*/
protected $_catalogProductCompareList;
/**
* Customer visitor
*
* @var MagentoCustomerModelVisitor
*/
protected $_customerVisitor;
/**
* Customer session
*
* @var MagentoCustomerModelSession
*/
protected $_customerSession;
/**
* Item collection factory
*
* @var MagentoCatalogModelResourceModelProductCompareItemCollectionFactory
*/
protected $_itemCollectionFactory;
/**
* Compare item factory
*
* @var MagentoCatalogModelProductCompareItemFactory
*/
protected $_compareItemFactory;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $_storeManager;
/**
* @var Validator
*/
protected $_formKeyValidator;
/**
* @var MagentoFrameworkViewResultPageFactory
*/
protected $resultPageFactory;
/**
* @var ProductRepositoryInterface
*/
protected $productRepository;
protected $_compareHelper;
protected $_urlInterface;
protected $_blockFactory;
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoCatalogModelProductCompareItemFactory $compareItemFactory,
MagentoCatalogModelResourceModelProductCompareItemCollectionFactory $itemCollectionFactory,
MagentoCustomerModelSession $customerSession,
MagentoCustomerModelVisitor $customerVisitor,
MagentoCatalogModelProductCompareListCompare $catalogProductCompareList,
MagentoCatalogModelSession $catalogSession,
MagentoStoreModelStoreManagerInterface $storeManager,
Validator $formKeyValidator,
PageFactory $resultPageFactory,
ProductRepositoryInterface $productRepository,
JsonFactory $resultJsonFactory,
EventManager $eventManager,
MagentoCatalogHelperProductCompare $compareHelper,
MagentoFrameworkUrlInterface $urlInterface,
MagentoFrameworkViewElementBlockFactory $blockFactory
) {
$this->resultJsonFactory = $resultJsonFactory;
$this->_storeManager = $storeManager;
$this->_compareItemFactory = $compareItemFactory;
$this->_itemCollectionFactory = $itemCollectionFactory;
$this->_customerSession = $customerSession;
$this->_customerVisitor = $customerVisitor;
$this->_catalogProductCompareList = $catalogProductCompareList;
$this->_catalogSession = $catalogSession;
$this->_formKeyValidator = $formKeyValidator;
$this->resultPageFactory = $resultPageFactory;
$this->productRepository = $productRepository;
$this->eventManager = $eventManager;
$this->_compareHelper = $compareHelper;
$this->_urlInterface = $urlInterface;
$this->_blockFactory = $blockFactory;
parent::__construct($context);
}
public function execute()
{
$resultJson = $this->resultJsonFactory->create();
$result = array();
$error = true;
$message = '';
// TODO: Validate this is a POST request.
$count = $this->_compareHelper->getItemCount();
if($count >= 4) {
$message = __('You can add the compared products under 4 item(s)');
$error = true;
return $resultJson->setData([
'message' => $message,
'data' => $result,
'error' => $error
]);
}
$productId = (int)$this->getRequest()->getParam('product');
if ($productId && ($this->_customerVisitor->getId() || $this->_customerSession->isLoggedIn())) {
$storeId = $this->_storeManager->getStore()->getId();
try {
$product = $this->productRepository->getById($productId, false, $storeId);
} catch (NoSuchEntityException $e) {
$product = null;
$message = __('Product does not exist');
$error = true;
}
if ($product) {
$this->_catalogProductCompareList->addProduct($product);
$this->_eventManager->dispatch('catalog_product_compare_add_product', ['product' => $product]);
}
$this->_objectManager->get('MagentoCatalogHelperProductCompare')->calculate();
$html = '';
if($this->_compareHelper->hasItems()){
$compItem = $this->_compareHelper->getItemCollection();
$i = 1;
$responseArray = array();
foreach($compItem->getData() as $comitem){
$productNew = $this->_objectManager->get('MagentoCatalogModelProduct')->load($comitem['entity_id']);
$imageBlock = $this->_blockFactory->createBlock('MagentoCatalogBlockProductListProduct');
$productImage = $imageBlock->getImage($productNew, 'product_comparison_list');
$imageUrl = $productImage->getImageUrl();
$responseArray[$i]['id'] = $comitem["entity_id"];
$responseArray[$i]['url'] = $imageUrl;
$i++;
}
for ($j = 1; $j <= 4; $j++)
{
if(isset($responseArray[$j]))
{
$html .= '<div class="compare-item active" data-itemid="'.$responseArray[$j]['id'].'">
<div class="compare-item-number">'. $j .'</div>
<a class="compare-item-remove removecompareajaxlink" href="javascript:void(0)" data-productid="'.$responseArray[$j]['id'].'" data-url="'. $this->_urlInterface->getUrl().'compareajax/index/removeCompare/product/'.$responseArray[$j]['id'] .'?isAjax=true"><i class="fa fa-remove"></i></a>
<img src="'. $responseArray[$j]['url'] .'" class="imageCompare" />
</div>';
}
else
{
$html .= '<div class="compare-item active" data-itemid="">
<div class="compare-item-number">'. $j .'</div>
</div>';
}
}
}
$message = __('Product successfully added in comparison list');
$result = array('html'=>$html,'id'=>$productId);
$error = false;
}
return $resultJson->setData([
'message' => $message,
'data' => $result,
'error' => $error
]);
}
}
Step 2. Please create another controller for removing the product as below.
<?php
namespace MagemonkeysCompareajaxControllerIndex;
use MagentoCatalogApiProductRepositoryInterface;
use MagentoFrameworkDataFormFormKeyValidator;
use MagentoFrameworkViewResultPageFactory;
use MagentoFrameworkControllerResultJsonFactory;
use MagentoFrameworkExceptionNoSuchEntityException;
use MagentoFrameworkEventManagerInterface as EventManager;
class RemoveCompare extends MagentoFrameworkAppActionAction
{
/**
* @var JsonFactory
*/
protected $resultJsonFactory;
/**
* @var EventManager
*/
private $eventManager;
/**
* Customer id
*
* @var null|int
*/
protected $_customerId = null;
/**
* Catalog session
*
* @var MagentoCatalogModelSession
*/
protected $_catalogSession;
/**
* Catalog product compare list
*
* @var MagentoCatalogModelProductCompareListCompare
*/
protected $_catalogProductCompareList;
/**
* Customer visitor
*
* @var MagentoCustomerModelVisitor
*/
protected $_customerVisitor;
/**
* Customer session
*
* @var MagentoCustomerModelSession
*/
protected $_customerSession;
/**
* Item collection factory
*
* @var MagentoCatalogModelResourceModelProductCompareItemCollectionFactory
*/
protected $_itemCollectionFactory;
/**
* Compare item factory
*
* @var MagentoCatalogModelProductCompareItemFactory
*/
protected $_compareItemFactory;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $_storeManager;
/**
* @var Validator
*/
protected $_formKeyValidator;
/**
* @var MagentoFrameworkViewResultPageFactory
*/
protected $resultPageFactory;
/**
* @var ProductRepositoryInterface
*/
protected $productRepository;
protected $_compareHelper;
protected $_urlInterface;
protected $_blockFactory;
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoCatalogModelProductCompareItemFactory $compareItemFactory,
MagentoCatalogModelResourceModelProductCompareItemCollectionFactory $itemCollectionFactory,
MagentoCustomerModelSession $customerSession,
MagentoCustomerModelVisitor $customerVisitor,
MagentoCatalogModelProductCompareListCompare $catalogProductCompareList,
MagentoCatalogModelSession $catalogSession,
MagentoStoreModelStoreManagerInterface $storeManager,
Validator $formKeyValidator,
PageFactory $resultPageFactory,
ProductRepositoryInterface $productRepository,
JsonFactory $resultJsonFactory,
EventManager $eventManager,
MagentoCatalogHelperProductCompare $compareHelper,
MagentoFrameworkUrlInterface $urlInterface,
MagentoFrameworkViewElementBlockFactory $blockFactory
) {
$this->resultJsonFactory = $resultJsonFactory;
$this->_storeManager = $storeManager;
$this->_compareItemFactory = $compareItemFactory;
$this->_itemCollectionFactory = $itemCollectionFactory;
$this->_customerSession = $customerSession;
$this->_customerVisitor = $customerVisitor;
$this->_catalogProductCompareList = $catalogProductCompareList;
$this->_catalogSession = $catalogSession;
$this->_formKeyValidator = $formKeyValidator;
$this->resultPageFactory = $resultPageFactory;
$this->productRepository = $productRepository;
$this->eventManager = $eventManager;
$this->_compareHelper = $compareHelper;
$this->_urlInterface = $urlInterface;
$this->_blockFactory = $blockFactory;
parent::__construct($context);
}
public function execute()
{
$resultJson = $this->resultJsonFactory->create();
$result = array();
$error = true;
$message = '';
// TODO: Validate this is a POST request.
$productId = (int)$this->getRequest()->getParam('product');
if ($productId) {
$storeId = $this->_storeManager->getStore()->getId();
try {
$product = $this->productRepository->getById($productId, false, $storeId);
} catch (NoSuchEntityException $e) {
$product = null;
$message = __('Product does not exist');
$error = true;
}
if ($product) {
$item = $this->_compareItemFactory->create();
if ($this->_customerSession->isLoggedIn()) {
$item->setCustomerId($this->_customerSession->getCustomerId());
} elseif ($this->_customerId) {
$item->setCustomerId($this->_customerId);
} else {
$item->addVisitorId($this->_customerVisitor->getId());
}
$item->loadByProduct($product);
if ($item->getId()) {
$item->delete();
$productName = $this->_objectManager->get(MagentoFrameworkEscaper::class)
->escapeHtml($product->getName());
$message = __('You removed product %1 from the comparison list.', $productName);
$this->_eventManager->dispatch('catalog_product_compare_remove_product',['product' => $item]);
$this->_objectManager->get('MagentoCatalogHelperProductCompare')->calculate();
}
$html = '';
if($this->_compareHelper->hasItems()){
$compItem = $this->_compareHelper->getItemCollection();
$i = 1;
$responseArray = array();
foreach($compItem->getData() as $comitem){
$productNew = $this->_objectManager->get('MagentoCatalogModelProduct')->load($comitem['entity_id']);
$imageBlock = $this->_blockFactory->createBlock('MagentoCatalogBlockProductListProduct');
$productImage = $imageBlock->getImage($productNew, 'product_comparison_list');
$imageUrl = $productImage->getImageUrl();
$responseArray[$i]['id'] = $comitem["entity_id"];
$responseArray[$i]['url'] = $imageUrl;
$i++;
}
for ($j = 1; $j <= 4; $j++)
{
if(isset($responseArray[$j]))
{
$html .= '<div class="compare-item active" data-itemid="'.$responseArray[$j]['id'].'">
<div class="compare-item-number">'. $j .'</div>
<a class="compare-item-remove removecompareajaxlink" href="javascript:void(0)" data-productid="'.$responseArray[$j]['id'].'" data-url="'. $this->_urlInterface->getUrl().'compareajax/index/removeCompare/product/'.$responseArray[$j]['id'] .'?isAjax=true"><i class="fa fa-remove"></i></a>
<img src="'. $responseArray[$j]['url'] .'" class="imageCompare" />
</div>';
}
else
{
$html .= '<div class="compare-item active" data-itemid="">
<div class="compare-item-number">'. $j .'</div>
</div>';
}
}
}
$message = __('You removed product from the comparison list.');
$result = array('html'=>$html,'id'=>$productId);
$error = false;
}
}
return $resultJson->setData([
'message' => $message,
'data' => $result,
'error' => $error
]);
}
}
You can execute and modify these controllers as per your requirements.

