We sacrifice by not doing any other technology, so that you get the best of Magento.

We sacrifice by not doing any other technology, so that you get the best of Magento.

    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.

    <?php echo $this->getLayout()->createBlock('MagentoFrameworkViewElementTemplate')->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.

    <referenceContainer name="after.body.start">
                <block class="MirasvitSearchAutocompleteBlockInjection" 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.

    <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”

    <?php
    
    namespace MagemonkeysCompareajaxControllerIndex;
    
    use MagentoCatalogApiProductRepositoryInterface;
    use MagentoFrameworkDataFormFormKeyValidator;
    use MagentoFrameworkViewResultPageFactory;
    use MagentoFrameworkControllerResultJsonFactory;
    use MagentoFrameworkExceptionNoSuchEntityException;
    use MagentoFrameworkEventManagerInterface as EventManager;
    
    class AddRemoveBoth 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.
    
            $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(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();
                    }
    
                    $removehtml = '';
                    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]))
                            {
                                $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('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
            ]);
        }
    }
    ?>

    You can change or modify the above steps as per your requirement.

     

    field_5bfb909c5ccae

      Get a Free Quote