Let’s initiate a discussion!!
Let’s say we want the compare page like GSM Arena Smartphone to compare tool in Magento 2.
So we have fixed the compare column in Magento at 4 as per our requirement. And we have added the search block to compare the list page.
We have achieved this type of functionality through Mirasvit Search Autocomplete.
Please follow the below steps.
Step 1: Add the search block in list.phtml of compare module by overriding the file in your theme or module and add the below code in the for each of compare item.
1 |
<?php echo $this->getLayout()->createBlock('Magento\Framework\View\Element\Template')->setTemplate('Magento_Search::form.mini.phtml')->toHtml(); ?> |
Step 2: You have to make the changes for the injection template so you have to add the below code of layout file which is “catalog_product_compare_index.xml”.
We have created a different injection template for compare list page so when you search the product and click on it it would not redirect so you can make an ajax call from it.
1 2 3 4 |
<referenceContainer name="after.body.start"> <block class="Mirasvit\SearchAutocomplete\Block\Injection" name="autocomplete.injection.template" as="autocomplete.injection.template" template="Mirasvit_SearchAutocomplete::injection_templates_compare.phtml"/> </referenceContainer> |
Step 3: You have to copy-paste the injection_template.phtml to code into injection_templates_compare.phtml file and remove the href from <a> tag to stop the redirection from search results.
step 4: Add the below script to list.phtml of compare module by overriding in your theme or module.
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 |
<script type="text/javascript"> require(['jquery'], function($){ /* For Add Product using Search on Compare page */ $(document).on('click', '.general', function(e){ var ttd = $(this).closest('td')[0]; //alert(ttd.id); var removeproductId = ttd.id; //alert(removeproductId); var productId = $(this).attr("id"); //alert(productId); var removeaddUrl = "<?php echo $this->getUrl();?>" + 'compareajax/index/addRemoveBoth/product/' + productId + '?isAjax=true'; //alert(removeaddUrl); jQuery.ajax({ url: removeaddUrl, type: "POST", dataType: 'json', data: { removeproduct: removeproductId, product: productId }, showLoader: true, success: function (response) { if(response.error == false) { // do something here location.reload(true); } else { alert(response.message); } }, error: function (response) { alert(response.message); } }); }); }); </script> |
Step 5: To remove the previous product and to add new searched product in the compare list create a front controller named “AddRemoveBoth.php” on this path “app/code/Magemonkeys/Compareajax/Controller/Index”
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 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
<?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 AddRemoveBoth 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. $removeproductId = (int)$this->getRequest()->getParam('removeproduct'); if ($removeproductId) { $storeId = $this->_storeManager->getStore()->getId(); try { $product = $this->productRepository->getById($removeproductId, 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(); } $removehtml = ''; 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])) { $removehtml .= '<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 { $removehtml .= '<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'=>$removehtml,'id'=>$removeproductId); $error = false; } } /*************************************************/ $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 ]); } } ?> |
You can change or modify the above steps as per your requirement.
[crayon-641f091c832a5423925271/] Using above fucntion Images can be imported directly from...
Override view block using di.xml and add the below code...
You can check a list of called layout XML for...
Follow the below steps to install and set up PWA...
If you want to remove all leading zero's from order,...
Let our Magento expert connect to discuss your requirement.
We offer Magento
certified developers.
Our Magento clientele
is 500+.
We sign NDA for the
security of your projects.
We’ve performed 100+
Magento migration projects.
Free quotation
on your project.
Three months warranty on
code developed by us.