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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 |
<?php namespace Magemonkeys\Compareajax\Controller\Index; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Framework\Data\Form\FormKey\Validator; use Magento\Framework\View\Result\PageFactory; use \Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Event\ManagerInterface as EventManager; class AddCompare extends \Magento\Framework\App\Action\Action { /** * @var JsonFactory */ protected $resultJsonFactory; /** * @var EventManager */ private $eventManager; /** * Customer id * * @var null|int */ protected $_customerId = null; /** * Catalog session * * @var \Magento\Catalog\Model\Session */ protected $_catalogSession; /** * Catalog product compare list * * @var \Magento\Catalog\Model\Product\Compare\ListCompare */ protected $_catalogProductCompareList; /** * Customer visitor * * @var \Magento\Customer\Model\Visitor */ protected $_customerVisitor; /** * Customer session * * @var \Magento\Customer\Model\Session */ protected $_customerSession; /** * Item collection factory * * @var \Magento\Catalog\Model\ResourceModel\Product\Compare\Item\CollectionFactory */ protected $_itemCollectionFactory; /** * Compare item factory * * @var \Magento\Catalog\Model\Product\Compare\ItemFactory */ protected $_compareItemFactory; /** * @var \Magento\Store\Model\StoreManagerInterface */ protected $_storeManager; /** * @var Validator */ protected $_formKeyValidator; /** * @var \Magento\Framework\View\Result\PageFactory */ protected $resultPageFactory; /** * @var ProductRepositoryInterface */ protected $productRepository; protected $_compareHelper; protected $_urlInterface; protected $_blockFactory; public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Catalog\Model\Product\Compare\ItemFactory $compareItemFactory, \Magento\Catalog\Model\ResourceModel\Product\Compare\Item\CollectionFactory $itemCollectionFactory, \Magento\Customer\Model\Session $customerSession, \Magento\Customer\Model\Visitor $customerVisitor, \Magento\Catalog\Model\Product\Compare\ListCompare $catalogProductCompareList, \Magento\Catalog\Model\Session $catalogSession, \Magento\Store\Model\StoreManagerInterface $storeManager, Validator $formKeyValidator, PageFactory $resultPageFactory, ProductRepositoryInterface $productRepository, JsonFactory $resultJsonFactory, EventManager $eventManager, \Magento\Catalog\Helper\Product\Compare $compareHelper, \Magento\Framework\UrlInterface $urlInterface, \Magento\Framework\View\Element\BlockFactory $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('Magento\Catalog\Helper\Product\Compare')->calculate(); $html = ''; if($this->_compareHelper->hasItems()){ $compItem = $this->_compareHelper->getItemCollection(); $i = 1; $responseArray = array(); foreach($compItem->getData() as $comitem){ $productNew = $this->_objectManager->get('Magento\Catalog\Model\Product')->load($comitem['entity_id']); $imageBlock = $this->_blockFactory->createBlock('Magento\Catalog\Block\Product\ListProduct'); $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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 |
<?php namespace Magemonkeys\Compareajax\Controller\Index; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Framework\Data\Form\FormKey\Validator; use Magento\Framework\View\Result\PageFactory; use \Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Event\ManagerInterface as EventManager; class RemoveCompare extends \Magento\Framework\App\Action\Action { /** * @var JsonFactory */ protected $resultJsonFactory; /** * @var EventManager */ private $eventManager; /** * Customer id * * @var null|int */ protected $_customerId = null; /** * Catalog session * * @var \Magento\Catalog\Model\Session */ protected $_catalogSession; /** * Catalog product compare list * * @var \Magento\Catalog\Model\Product\Compare\ListCompare */ protected $_catalogProductCompareList; /** * Customer visitor * * @var \Magento\Customer\Model\Visitor */ protected $_customerVisitor; /** * Customer session * * @var \Magento\Customer\Model\Session */ protected $_customerSession; /** * Item collection factory * * @var \Magento\Catalog\Model\ResourceModel\Product\Compare\Item\CollectionFactory */ protected $_itemCollectionFactory; /** * Compare item factory * * @var \Magento\Catalog\Model\Product\Compare\ItemFactory */ protected $_compareItemFactory; /** * @var \Magento\Store\Model\StoreManagerInterface */ protected $_storeManager; /** * @var Validator */ protected $_formKeyValidator; /** * @var \Magento\Framework\View\Result\PageFactory */ protected $resultPageFactory; /** * @var ProductRepositoryInterface */ protected $productRepository; protected $_compareHelper; protected $_urlInterface; protected $_blockFactory; public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Catalog\Model\Product\Compare\ItemFactory $compareItemFactory, \Magento\Catalog\Model\ResourceModel\Product\Compare\Item\CollectionFactory $itemCollectionFactory, \Magento\Customer\Model\Session $customerSession, \Magento\Customer\Model\Visitor $customerVisitor, \Magento\Catalog\Model\Product\Compare\ListCompare $catalogProductCompareList, \Magento\Catalog\Model\Session $catalogSession, \Magento\Store\Model\StoreManagerInterface $storeManager, Validator $formKeyValidator, PageFactory $resultPageFactory, ProductRepositoryInterface $productRepository, JsonFactory $resultJsonFactory, EventManager $eventManager, \Magento\Catalog\Helper\Product\Compare $compareHelper, \Magento\Framework\UrlInterface $urlInterface, \Magento\Framework\View\Element\BlockFactory $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(\Magento\Framework\Escaper::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('Magento\Catalog\Helper\Product\Compare')->calculate(); } $html = ''; if($this->_compareHelper->hasItems()){ $compItem = $this->_compareHelper->getItemCollection(); $i = 1; $responseArray = array(); foreach($compItem->getData() as $comitem){ $productNew = $this->_objectManager->get('Magento\Catalog\Model\Product')->load($comitem['entity_id']); $imageBlock = $this->_blockFactory->createBlock('Magento\Catalog\Block\Product\ListProduct'); $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.
Please follow the below methods to get the attribute options...
Update product attribute value programmatically in Magento 2 . [crayon-628776a4b16c3792872656/]...
If you want restrict customer to checkout based on your...
Sometime we need to set html data without load or...
If you want get query string params in controller file,...