I want to get product collection for current category while I am on a list page.
I want to get current product collection for current category while ajax call (i want the same collection in the controller which return some data based on collection) so is there any way that I can get the same product collection which was used in list.phtml
Here is code, which returns product collection but results not match 100%
namespace Vendor\Module\Controller\Index;
use Magento\Framework\App\Action\Context;
class Model extends \Magento\Framework\App\Action\Action
{
protected $resultJsonFactory;
protected $request;
protected $store_manager;
protected $productRepository;
protected $searchCriteriaBuilder;
protected $eavConfig;
public function __construct(
Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Magento\Framework\App\RequestInterface $request,
\Magento\Store\Model\StoreManagerInterface $store_manager,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collection,
\Magento\Catalog\Model\CategoryRepository $categoryRepository,
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
\Magento\Eav\Model\Config $eavConfig)
{
$this->request = $request;
$this->resultJsonFactory = $resultJsonFactory;
$this->store_manager = $store_manager;
$this->productRepository = $productRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->eavConfig = $eavConfig;
$this->productCollection = $collection;
$this->categoryRepository = $categoryRepository;
$this->_categoryFactory = $categoryFactory;
parent::__construct($context);
}
public function execute()
{
$data = $this->request->getParams();
$parent_category_id = $data['current_category_id'];
$productsCollection=$this->getProductCollection($parent_category_id);
$productsCollection->addAttributeToFilter('make',array('in'=>array(floatval($data['make']))));
}
private function getStoreCode()
{
return $this->store_manager->getStore()->getCode();
}
public function getProductCollection($categoryId)
{
$category = $this->_categoryFactory->create()->load($categoryId);
$collection = $this->productCollection->create();
$collection->addAttributeToSelect('*');
$collection->addCategoryFilter($category);
$collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
$collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
return $collection;
}
}
Does anyone have any idea how can I achieve my above requirement?
Thanks