/** * {@inheritdoc} */ protected function _prepareCollection() { if ($this->getParam('website')) { $storeIds = $this->_storeManager->getWebsite($this->getParam('website'))->getStoreIds(); $storeId = array_pop($storeIds); } elseif ($this->getParam('group')) { $storeIds = $this->_storeManager->getGroup($this->getParam('group'))->getStoreIds(); $storeId = array_pop($storeIds); } else { $storeId = (int) $this->getParam('store'); } $collection = $this->_productsFactory->create()->addAttributeToSelect('*')->addViewsCount()->setStoreId($storeId)->addStoreFilter($storeId); $this->setCollection($collection); return parent::_prepareCollection(); }
/** * Get product collection. * * @return array */ public function getLoadedProductCollection() { $productsToDisplay = []; $mode = $this->getRequest()->getActionName(); $limit = $this->recommnededHelper->getDisplayLimitByMode($mode); $from = $this->recommnededHelper->getTimeFromConfig($mode); $to = $this->_localeDate->date()->format(\Zend_Date::ISO_8601); $reportProductCollection = $this->reportProductCollection->create()->addViewsCount($from, $to)->setPageSize($limit); //filter collection by category by category_id if ($catId = $this->getRequest()->getParam('category_id')) { $category = $this->categoryFactory->create()->load($catId); if ($category->getId()) { $reportProductCollection->getSelect()->joinLeft(['ccpi' => $this->coreResource->getTableName('catalog_category_product_index')], 'e.entity_id = ccpi.product_id', ['category_id'])->where('ccpi.category_id =?', $catId); } else { $this->helper->log('Most viewed. Category id ' . $catId . ' is invalid. It does not exist.'); } } //filter collection by category by category_name if ($catName = $this->getRequest()->getParam('category_name')) { $category = $this->categoryFactory->create()->loadByAttribute('name', $catName); if ($category) { $reportProductCollection->getSelect()->joinLeft(['ccpi' => $this->coreResource->getTableName('catalog_category_product_index')], 'e.entity_id = ccpi.product_id', ['category_id'])->where('ccpi.category_id =?', $category->getId()); } else { $this->helper->log('Most viewed. Category name ' . $catName . ' is invalid. It does not exist.'); } } //product ids from the report product collection $productIds = $reportProductCollection->getColumnValues('entity_id'); $productCollectionFactory = $this->productCollectionFactory->create(); $productCollectionFactory->addIdFilter($productIds)->addAttributeToSelect(['product_url', 'name', 'store_id', 'small_image', 'price']); //product collection foreach ($productCollectionFactory as $_product) { //add only saleable products if ($_product->isSalable()) { $productsToDisplay[] = $_product; } } return $productsToDisplay; }