#StackBounty: #magento2 #collection #layered-navigation #ratings Magento 2 layer navigation custom rating filter pagination doesn't…

Bounty: 50

I have created a module for rating filter and its working but after filter number of item and pagination showing wrong as per attached screenshot.

There is only one 5 start product but showing wrong item and pagination.

Below is the code which is developed by me:

app/code/Namespace/Catalog/Model/Layer/Filter/Rating.php

<?php

/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace NamespaceCatalogModelLayerFilter;

use MagentoCatalogModelCategory as CategoryModel;
use MagentoCatalogModelCategoryFactory as CategoryModelFactory;
use MagentoCatalogModelLayer;
use MagentoFrameworkRegistry;

/**
 * Layer category filter
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Rating extends MagentoCatalogModelLayerFilterAbstractFilter {

    /**
     * Active Category Id
     *
     * @var int
     */
    protected $_categoryId;

    /**
     * Applied Category
     *
     * @var MagentoCatalogModelCategory
     */
    protected $_appliedCategory;

    /**
     * Core data
     *
     * @var MagentoFrameworkEscaper
     */
    protected $_escaper;

    /**
     * Core registry
     *
     * @var MagentoFrameworkRegistry
     */
    protected $_coreRegistry;

    /**
     * @var CategoryDataProvider
     */
    private $dataProvider;

    /**
     * Construct
     *
     * @param MagentoCatalogModelLayerFilterItemFactory $filterItemFactory
     * @param MagentoStoreModelStoreManagerInterface $storeManager
     * @param MagentoCatalogModelLayer $layer
     * @param MagentoCatalogModelLayerFilterItemDataBuilder $itemDataBuilder
     * @param MagentoFrameworkEscaper $escaper
     * @param CategoryFactory $categoryDataProviderFactory
     * @param array $data
     */
    public function __construct(
    MagentoCatalogModelLayerFilterItemFactory $filterItemFactory,
    MagentoStoreModelStoreManagerInterface $storeManager, 
    MagentoCatalogModelLayer $layer, 
    MagentoCatalogModelLayerFilterItemDataBuilder $itemDataBuilder, 
    MagentoFrameworkEscaper $escaper, 
    MagentoFrameworkObjectManagerInterface $objectManager, 
    MagentoCatalogModelProduct $productModel, 
    MagentoCatalogModelProductAttributeSourceStatus $productStatus, 
    MagentoCatalogModelProductVisibility $productVisibility, 
    MagentoStoreModelStoreManagerInterface $storeManager,            
    array $data = []
    ) {
         $this->_storeManager = $storeManager;        
        parent::__construct($filterItemFactory, $storeManager, $layer, $itemDataBuilder, $data);
        $this->_escaper = $escaper;
        $this->objectManager = $objectManager;
        $this->_productModel = $productModel;
        $this->productStatus = $productStatus;
        $this->productVisibility = $productVisibility;
         $this->_requestVar = 'rating';
    }

    protected $stars = array(
        1 => 20,
        2 => 40,
        3 => 60,
        4 => 80,
        5 => 100,
    );    

    /**
     * Get filter value for reset current filter state
     *
     * @return mixed|null
     */


    /**
     * Apply category filter to layer
     *
     * @param   MagentoFrameworkAppRequestInterface $request
     * @return  $this
     */
    public function apply(MagentoFrameworkAppRequestInterface $request) {
        /**
         * Filter must be string: $fromPrice-$toPrice
         */
        $filter = $request->getParam($this->getRequestVar());
        if (!$filter) {
            return $this;
        }
        $collection = $this->getLayer()->getProductCollection();
        $select = $collection->getSelect();
        $minRating = (array_key_exists($filter, $this->stars))
            ? $this->stars[$filter]
            : 0;
        $reviewSummary = 'review_entity_summary';
        $select->joinLeft(
            array('rating' => $reviewSummary),
            sprintf('`rating`.`entity_pk_value`=`e`.entity_id
                    AND `rating`.`entity_type` = 1
                    AND `rating`.`store_id`  =  %d',
                $this->_storeManager->getStore()->getId()
            ),
            ''
        );
        $select->where('`rating`.`rating_summary` >= ?',
            $minRating);
        $state = $this->_createItem($this->getLabelHtml($filter), $filter)
                      ->setVar($this->_requestVar);
        $this->getLayer()->getState()->addFilter($state);


        return $this;
    }

    /**
     * Get filter name
     *
     * @return MagentoFrameworkPhrase
     */
    public function getName() {
        return __('Rating');
    }

    protected function _getItemsData()
    {   
        $data = array();
        $count = $this->_getCount();

        $currentValue = $this->getRequestVar();
        for ($i=1;$i<=5;$i++) {
            $data[] = array(
                'label' => $this->getLabelHtml($i),
                'value' => ($currentValue == $i) ? null : $i,
                'count' => $count[($i-1)],
                'option_id' => $i,
            );
        }
        return $data;
    }
    /**
     * @return array
     */
    protected function _getCount()
    {
        $collection = $this->getLayer()->getProductCollection();
        $connection = $collection->getConnection();
        $connection
            ->query('SET @ONE :=0, @TWO := 0, @THREE := 0, @FOUR := 0, @FIVE := 0');
        $select = clone $collection->getSelect();

        $select->reset(Zend_Db_Select::COLUMNS);
        $select->reset(Zend_Db_Select::ORDER);
        $select->reset(Zend_Db_Select::LIMIT_COUNT);
        $select->reset(Zend_Db_Select::LIMIT_OFFSET);
        $select->reset(Zend_Db_Select::WHERE);      
        $reviewSummary = 'review_entity_summary';
        $select->joinLeft(
            array('rsc' => $reviewSummary),
            sprintf('`rsc`.`entity_pk_value`=`e`.entity_id
                AND `rsc`.entity_type = 1
                AND `rsc`.store_id  =  %d',
                $this->_storeManager->getStore()->getId()),
            'rsc.rating_summary AS rating'
        );
        $columns = new Zend_Db_Expr("
            IF(`rsc`.`rating_summary` <  40, @ONE := @ONE + 1, 0),
            IF(`rsc`.`rating_summary` >= 40 AND `rsc`.`rating_summary` < 60, @TWO := @TWO + 1, 0),
            IF(`rsc`.`rating_summary` >= 60 AND `rsc`.`rating_summary` < 80, @THREE := @THREE + 1, 0),
            IF(`rsc`.`rating_summary` >= 80 AND `rsc`.`rating_summary` < 100, @FOUR := @FOUR + 1, 0),
            IF(`rsc`.`rating_summary` >= 100, @FIVE := @FIVE + 1, 0)
        ");
        $select->columns($columns);
        $connection->query($select);
        $result = $connection->fetchRow('SELECT @ONE, @TWO, @THREE, @FOUR, @FIVE;');
        return array_values($result);
    }
    protected function _initItems()
    {   
        $data  = $this->_getItemsData();

        $items = array();
        foreach ($data as $itemData) {
            $item = $this->_createItem(
                $itemData['label'],
                $itemData['value'],
                $itemData['count']
            );
            $item->setOptionId($itemData['option_id']);
            $items[] = $item;
        }
        $this->_items = $items;

        return $this;
    }

    protected function getLabelHtml($countStars)
    {
         $html = '
</div>'; return $html; } } ?>

enter image description here


Get this bounty!!!

#StackBounty: #magento2 #collection #layered-navigation #ratings Magento 2 layer navigation custom rating filter pagination doesn't…

Bounty: 50

I have created a module for rating filter and its working but after filter number of item and pagination showing wrong as per attached screenshot.

There is only one 5 start product but showing wrong item and pagination.

Below is the code which is developed by me:

app/code/Namespace/Catalog/Model/Layer/Filter/Rating.php

<?php

/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace NamespaceCatalogModelLayerFilter;

use MagentoCatalogModelCategory as CategoryModel;
use MagentoCatalogModelCategoryFactory as CategoryModelFactory;
use MagentoCatalogModelLayer;
use MagentoFrameworkRegistry;

/**
 * Layer category filter
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Rating extends MagentoCatalogModelLayerFilterAbstractFilter {

    /**
     * Active Category Id
     *
     * @var int
     */
    protected $_categoryId;

    /**
     * Applied Category
     *
     * @var MagentoCatalogModelCategory
     */
    protected $_appliedCategory;

    /**
     * Core data
     *
     * @var MagentoFrameworkEscaper
     */
    protected $_escaper;

    /**
     * Core registry
     *
     * @var MagentoFrameworkRegistry
     */
    protected $_coreRegistry;

    /**
     * @var CategoryDataProvider
     */
    private $dataProvider;

    /**
     * Construct
     *
     * @param MagentoCatalogModelLayerFilterItemFactory $filterItemFactory
     * @param MagentoStoreModelStoreManagerInterface $storeManager
     * @param MagentoCatalogModelLayer $layer
     * @param MagentoCatalogModelLayerFilterItemDataBuilder $itemDataBuilder
     * @param MagentoFrameworkEscaper $escaper
     * @param CategoryFactory $categoryDataProviderFactory
     * @param array $data
     */
    public function __construct(
    MagentoCatalogModelLayerFilterItemFactory $filterItemFactory,
    MagentoStoreModelStoreManagerInterface $storeManager, 
    MagentoCatalogModelLayer $layer, 
    MagentoCatalogModelLayerFilterItemDataBuilder $itemDataBuilder, 
    MagentoFrameworkEscaper $escaper, 
    MagentoFrameworkObjectManagerInterface $objectManager, 
    MagentoCatalogModelProduct $productModel, 
    MagentoCatalogModelProductAttributeSourceStatus $productStatus, 
    MagentoCatalogModelProductVisibility $productVisibility, 
    MagentoStoreModelStoreManagerInterface $storeManager,            
    array $data = []
    ) {
         $this->_storeManager = $storeManager;        
        parent::__construct($filterItemFactory, $storeManager, $layer, $itemDataBuilder, $data);
        $this->_escaper = $escaper;
        $this->objectManager = $objectManager;
        $this->_productModel = $productModel;
        $this->productStatus = $productStatus;
        $this->productVisibility = $productVisibility;
         $this->_requestVar = 'rating';
    }

    protected $stars = array(
        1 => 20,
        2 => 40,
        3 => 60,
        4 => 80,
        5 => 100,
    );    

    /**
     * Get filter value for reset current filter state
     *
     * @return mixed|null
     */


    /**
     * Apply category filter to layer
     *
     * @param   MagentoFrameworkAppRequestInterface $request
     * @return  $this
     */
    public function apply(MagentoFrameworkAppRequestInterface $request) {
        /**
         * Filter must be string: $fromPrice-$toPrice
         */
        $filter = $request->getParam($this->getRequestVar());
        if (!$filter) {
            return $this;
        }
        $collection = $this->getLayer()->getProductCollection();
        $select = $collection->getSelect();
        $minRating = (array_key_exists($filter, $this->stars))
            ? $this->stars[$filter]
            : 0;
        $reviewSummary = 'review_entity_summary';
        $select->joinLeft(
            array('rating' => $reviewSummary),
            sprintf('`rating`.`entity_pk_value`=`e`.entity_id
                    AND `rating`.`entity_type` = 1
                    AND `rating`.`store_id`  =  %d',
                $this->_storeManager->getStore()->getId()
            ),
            ''
        );
        $select->where('`rating`.`rating_summary` >= ?',
            $minRating);
        $state = $this->_createItem($this->getLabelHtml($filter), $filter)
                      ->setVar($this->_requestVar);
        $this->getLayer()->getState()->addFilter($state);


        return $this;
    }

    /**
     * Get filter name
     *
     * @return MagentoFrameworkPhrase
     */
    public function getName() {
        return __('Rating');
    }

    protected function _getItemsData()
    {   
        $data = array();
        $count = $this->_getCount();

        $currentValue = $this->getRequestVar();
        for ($i=1;$i<=5;$i++) {
            $data[] = array(
                'label' => $this->getLabelHtml($i),
                'value' => ($currentValue == $i) ? null : $i,
                'count' => $count[($i-1)],
                'option_id' => $i,
            );
        }
        return $data;
    }
    /**
     * @return array
     */
    protected function _getCount()
    {
        $collection = $this->getLayer()->getProductCollection();
        $connection = $collection->getConnection();
        $connection
            ->query('SET @ONE :=0, @TWO := 0, @THREE := 0, @FOUR := 0, @FIVE := 0');
        $select = clone $collection->getSelect();

        $select->reset(Zend_Db_Select::COLUMNS);
        $select->reset(Zend_Db_Select::ORDER);
        $select->reset(Zend_Db_Select::LIMIT_COUNT);
        $select->reset(Zend_Db_Select::LIMIT_OFFSET);
        $select->reset(Zend_Db_Select::WHERE);      
        $reviewSummary = 'review_entity_summary';
        $select->joinLeft(
            array('rsc' => $reviewSummary),
            sprintf('`rsc`.`entity_pk_value`=`e`.entity_id
                AND `rsc`.entity_type = 1
                AND `rsc`.store_id  =  %d',
                $this->_storeManager->getStore()->getId()),
            'rsc.rating_summary AS rating'
        );
        $columns = new Zend_Db_Expr("
            IF(`rsc`.`rating_summary` <  40, @ONE := @ONE + 1, 0),
            IF(`rsc`.`rating_summary` >= 40 AND `rsc`.`rating_summary` < 60, @TWO := @TWO + 1, 0),
            IF(`rsc`.`rating_summary` >= 60 AND `rsc`.`rating_summary` < 80, @THREE := @THREE + 1, 0),
            IF(`rsc`.`rating_summary` >= 80 AND `rsc`.`rating_summary` < 100, @FOUR := @FOUR + 1, 0),
            IF(`rsc`.`rating_summary` >= 100, @FIVE := @FIVE + 1, 0)
        ");
        $select->columns($columns);
        $connection->query($select);
        $result = $connection->fetchRow('SELECT @ONE, @TWO, @THREE, @FOUR, @FIVE;');
        return array_values($result);
    }
    protected function _initItems()
    {   
        $data  = $this->_getItemsData();

        $items = array();
        foreach ($data as $itemData) {
            $item = $this->_createItem(
                $itemData['label'],
                $itemData['value'],
                $itemData['count']
            );
            $item->setOptionId($itemData['option_id']);
            $items[] = $item;
        }
        $this->_items = $items;

        return $this;
    }

    protected function getLabelHtml($countStars)
    {
         $html = '
</div>'; return $html; } } ?>

enter image description here


Get this bounty!!!

#StackBounty: #magento2 #collection #layered-navigation #ratings Magento 2 layer navigation custom rating filter pagination doesn't…

Bounty: 50

I have created a module for rating filter and its working but after filter number of item and pagination showing wrong as per attached screenshot.

There is only one 5 start product but showing wrong item and pagination.

Below is the code which is developed by me:

app/code/Namespace/Catalog/Model/Layer/Filter/Rating.php

<?php

/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace NamespaceCatalogModelLayerFilter;

use MagentoCatalogModelCategory as CategoryModel;
use MagentoCatalogModelCategoryFactory as CategoryModelFactory;
use MagentoCatalogModelLayer;
use MagentoFrameworkRegistry;

/**
 * Layer category filter
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Rating extends MagentoCatalogModelLayerFilterAbstractFilter {

    /**
     * Active Category Id
     *
     * @var int
     */
    protected $_categoryId;

    /**
     * Applied Category
     *
     * @var MagentoCatalogModelCategory
     */
    protected $_appliedCategory;

    /**
     * Core data
     *
     * @var MagentoFrameworkEscaper
     */
    protected $_escaper;

    /**
     * Core registry
     *
     * @var MagentoFrameworkRegistry
     */
    protected $_coreRegistry;

    /**
     * @var CategoryDataProvider
     */
    private $dataProvider;

    /**
     * Construct
     *
     * @param MagentoCatalogModelLayerFilterItemFactory $filterItemFactory
     * @param MagentoStoreModelStoreManagerInterface $storeManager
     * @param MagentoCatalogModelLayer $layer
     * @param MagentoCatalogModelLayerFilterItemDataBuilder $itemDataBuilder
     * @param MagentoFrameworkEscaper $escaper
     * @param CategoryFactory $categoryDataProviderFactory
     * @param array $data
     */
    public function __construct(
    MagentoCatalogModelLayerFilterItemFactory $filterItemFactory,
    MagentoStoreModelStoreManagerInterface $storeManager, 
    MagentoCatalogModelLayer $layer, 
    MagentoCatalogModelLayerFilterItemDataBuilder $itemDataBuilder, 
    MagentoFrameworkEscaper $escaper, 
    MagentoFrameworkObjectManagerInterface $objectManager, 
    MagentoCatalogModelProduct $productModel, 
    MagentoCatalogModelProductAttributeSourceStatus $productStatus, 
    MagentoCatalogModelProductVisibility $productVisibility, 
    MagentoStoreModelStoreManagerInterface $storeManager,            
    array $data = []
    ) {
         $this->_storeManager = $storeManager;        
        parent::__construct($filterItemFactory, $storeManager, $layer, $itemDataBuilder, $data);
        $this->_escaper = $escaper;
        $this->objectManager = $objectManager;
        $this->_productModel = $productModel;
        $this->productStatus = $productStatus;
        $this->productVisibility = $productVisibility;
         $this->_requestVar = 'rating';
    }

    protected $stars = array(
        1 => 20,
        2 => 40,
        3 => 60,
        4 => 80,
        5 => 100,
    );    

    /**
     * Get filter value for reset current filter state
     *
     * @return mixed|null
     */


    /**
     * Apply category filter to layer
     *
     * @param   MagentoFrameworkAppRequestInterface $request
     * @return  $this
     */
    public function apply(MagentoFrameworkAppRequestInterface $request) {
        /**
         * Filter must be string: $fromPrice-$toPrice
         */
        $filter = $request->getParam($this->getRequestVar());
        if (!$filter) {
            return $this;
        }
        $collection = $this->getLayer()->getProductCollection();
        $select = $collection->getSelect();
        $minRating = (array_key_exists($filter, $this->stars))
            ? $this->stars[$filter]
            : 0;
        $reviewSummary = 'review_entity_summary';
        $select->joinLeft(
            array('rating' => $reviewSummary),
            sprintf('`rating`.`entity_pk_value`=`e`.entity_id
                    AND `rating`.`entity_type` = 1
                    AND `rating`.`store_id`  =  %d',
                $this->_storeManager->getStore()->getId()
            ),
            ''
        );
        $select->where('`rating`.`rating_summary` >= ?',
            $minRating);
        $state = $this->_createItem($this->getLabelHtml($filter), $filter)
                      ->setVar($this->_requestVar);
        $this->getLayer()->getState()->addFilter($state);


        return $this;
    }

    /**
     * Get filter name
     *
     * @return MagentoFrameworkPhrase
     */
    public function getName() {
        return __('Rating');
    }

    protected function _getItemsData()
    {   
        $data = array();
        $count = $this->_getCount();

        $currentValue = $this->getRequestVar();
        for ($i=1;$i<=5;$i++) {
            $data[] = array(
                'label' => $this->getLabelHtml($i),
                'value' => ($currentValue == $i) ? null : $i,
                'count' => $count[($i-1)],
                'option_id' => $i,
            );
        }
        return $data;
    }
    /**
     * @return array
     */
    protected function _getCount()
    {
        $collection = $this->getLayer()->getProductCollection();
        $connection = $collection->getConnection();
        $connection
            ->query('SET @ONE :=0, @TWO := 0, @THREE := 0, @FOUR := 0, @FIVE := 0');
        $select = clone $collection->getSelect();

        $select->reset(Zend_Db_Select::COLUMNS);
        $select->reset(Zend_Db_Select::ORDER);
        $select->reset(Zend_Db_Select::LIMIT_COUNT);
        $select->reset(Zend_Db_Select::LIMIT_OFFSET);
        $select->reset(Zend_Db_Select::WHERE);      
        $reviewSummary = 'review_entity_summary';
        $select->joinLeft(
            array('rsc' => $reviewSummary),
            sprintf('`rsc`.`entity_pk_value`=`e`.entity_id
                AND `rsc`.entity_type = 1
                AND `rsc`.store_id  =  %d',
                $this->_storeManager->getStore()->getId()),
            'rsc.rating_summary AS rating'
        );
        $columns = new Zend_Db_Expr("
            IF(`rsc`.`rating_summary` <  40, @ONE := @ONE + 1, 0),
            IF(`rsc`.`rating_summary` >= 40 AND `rsc`.`rating_summary` < 60, @TWO := @TWO + 1, 0),
            IF(`rsc`.`rating_summary` >= 60 AND `rsc`.`rating_summary` < 80, @THREE := @THREE + 1, 0),
            IF(`rsc`.`rating_summary` >= 80 AND `rsc`.`rating_summary` < 100, @FOUR := @FOUR + 1, 0),
            IF(`rsc`.`rating_summary` >= 100, @FIVE := @FIVE + 1, 0)
        ");
        $select->columns($columns);
        $connection->query($select);
        $result = $connection->fetchRow('SELECT @ONE, @TWO, @THREE, @FOUR, @FIVE;');
        return array_values($result);
    }
    protected function _initItems()
    {   
        $data  = $this->_getItemsData();

        $items = array();
        foreach ($data as $itemData) {
            $item = $this->_createItem(
                $itemData['label'],
                $itemData['value'],
                $itemData['count']
            );
            $item->setOptionId($itemData['option_id']);
            $items[] = $item;
        }
        $this->_items = $items;

        return $this;
    }

    protected function getLabelHtml($countStars)
    {
         $html = '
</div>'; return $html; } } ?>

enter image description here


Get this bounty!!!

#StackBounty: #magento2 #collection #layered-navigation #ratings Magento 2 layer navigation custom rating filter pagination doesn't…

Bounty: 50

I have created a module for rating filter and its working but after filter number of item and pagination showing wrong as per attached screenshot.

There is only one 5 start product but showing wrong item and pagination.

Below is the code which is developed by me:

app/code/Namespace/Catalog/Model/Layer/Filter/Rating.php

<?php

/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace NamespaceCatalogModelLayerFilter;

use MagentoCatalogModelCategory as CategoryModel;
use MagentoCatalogModelCategoryFactory as CategoryModelFactory;
use MagentoCatalogModelLayer;
use MagentoFrameworkRegistry;

/**
 * Layer category filter
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Rating extends MagentoCatalogModelLayerFilterAbstractFilter {

    /**
     * Active Category Id
     *
     * @var int
     */
    protected $_categoryId;

    /**
     * Applied Category
     *
     * @var MagentoCatalogModelCategory
     */
    protected $_appliedCategory;

    /**
     * Core data
     *
     * @var MagentoFrameworkEscaper
     */
    protected $_escaper;

    /**
     * Core registry
     *
     * @var MagentoFrameworkRegistry
     */
    protected $_coreRegistry;

    /**
     * @var CategoryDataProvider
     */
    private $dataProvider;

    /**
     * Construct
     *
     * @param MagentoCatalogModelLayerFilterItemFactory $filterItemFactory
     * @param MagentoStoreModelStoreManagerInterface $storeManager
     * @param MagentoCatalogModelLayer $layer
     * @param MagentoCatalogModelLayerFilterItemDataBuilder $itemDataBuilder
     * @param MagentoFrameworkEscaper $escaper
     * @param CategoryFactory $categoryDataProviderFactory
     * @param array $data
     */
    public function __construct(
    MagentoCatalogModelLayerFilterItemFactory $filterItemFactory,
    MagentoStoreModelStoreManagerInterface $storeManager, 
    MagentoCatalogModelLayer $layer, 
    MagentoCatalogModelLayerFilterItemDataBuilder $itemDataBuilder, 
    MagentoFrameworkEscaper $escaper, 
    MagentoFrameworkObjectManagerInterface $objectManager, 
    MagentoCatalogModelProduct $productModel, 
    MagentoCatalogModelProductAttributeSourceStatus $productStatus, 
    MagentoCatalogModelProductVisibility $productVisibility, 
    MagentoStoreModelStoreManagerInterface $storeManager,            
    array $data = []
    ) {
         $this->_storeManager = $storeManager;        
        parent::__construct($filterItemFactory, $storeManager, $layer, $itemDataBuilder, $data);
        $this->_escaper = $escaper;
        $this->objectManager = $objectManager;
        $this->_productModel = $productModel;
        $this->productStatus = $productStatus;
        $this->productVisibility = $productVisibility;
         $this->_requestVar = 'rating';
    }

    protected $stars = array(
        1 => 20,
        2 => 40,
        3 => 60,
        4 => 80,
        5 => 100,
    );    

    /**
     * Get filter value for reset current filter state
     *
     * @return mixed|null
     */


    /**
     * Apply category filter to layer
     *
     * @param   MagentoFrameworkAppRequestInterface $request
     * @return  $this
     */
    public function apply(MagentoFrameworkAppRequestInterface $request) {
        /**
         * Filter must be string: $fromPrice-$toPrice
         */
        $filter = $request->getParam($this->getRequestVar());
        if (!$filter) {
            return $this;
        }
        $collection = $this->getLayer()->getProductCollection();
        $select = $collection->getSelect();
        $minRating = (array_key_exists($filter, $this->stars))
            ? $this->stars[$filter]
            : 0;
        $reviewSummary = 'review_entity_summary';
        $select->joinLeft(
            array('rating' => $reviewSummary),
            sprintf('`rating`.`entity_pk_value`=`e`.entity_id
                    AND `rating`.`entity_type` = 1
                    AND `rating`.`store_id`  =  %d',
                $this->_storeManager->getStore()->getId()
            ),
            ''
        );
        $select->where('`rating`.`rating_summary` >= ?',
            $minRating);
        $state = $this->_createItem($this->getLabelHtml($filter), $filter)
                      ->setVar($this->_requestVar);
        $this->getLayer()->getState()->addFilter($state);


        return $this;
    }

    /**
     * Get filter name
     *
     * @return MagentoFrameworkPhrase
     */
    public function getName() {
        return __('Rating');
    }

    protected function _getItemsData()
    {   
        $data = array();
        $count = $this->_getCount();

        $currentValue = $this->getRequestVar();
        for ($i=1;$i<=5;$i++) {
            $data[] = array(
                'label' => $this->getLabelHtml($i),
                'value' => ($currentValue == $i) ? null : $i,
                'count' => $count[($i-1)],
                'option_id' => $i,
            );
        }
        return $data;
    }
    /**
     * @return array
     */
    protected function _getCount()
    {
        $collection = $this->getLayer()->getProductCollection();
        $connection = $collection->getConnection();
        $connection
            ->query('SET @ONE :=0, @TWO := 0, @THREE := 0, @FOUR := 0, @FIVE := 0');
        $select = clone $collection->getSelect();

        $select->reset(Zend_Db_Select::COLUMNS);
        $select->reset(Zend_Db_Select::ORDER);
        $select->reset(Zend_Db_Select::LIMIT_COUNT);
        $select->reset(Zend_Db_Select::LIMIT_OFFSET);
        $select->reset(Zend_Db_Select::WHERE);      
        $reviewSummary = 'review_entity_summary';
        $select->joinLeft(
            array('rsc' => $reviewSummary),
            sprintf('`rsc`.`entity_pk_value`=`e`.entity_id
                AND `rsc`.entity_type = 1
                AND `rsc`.store_id  =  %d',
                $this->_storeManager->getStore()->getId()),
            'rsc.rating_summary AS rating'
        );
        $columns = new Zend_Db_Expr("
            IF(`rsc`.`rating_summary` <  40, @ONE := @ONE + 1, 0),
            IF(`rsc`.`rating_summary` >= 40 AND `rsc`.`rating_summary` < 60, @TWO := @TWO + 1, 0),
            IF(`rsc`.`rating_summary` >= 60 AND `rsc`.`rating_summary` < 80, @THREE := @THREE + 1, 0),
            IF(`rsc`.`rating_summary` >= 80 AND `rsc`.`rating_summary` < 100, @FOUR := @FOUR + 1, 0),
            IF(`rsc`.`rating_summary` >= 100, @FIVE := @FIVE + 1, 0)
        ");
        $select->columns($columns);
        $connection->query($select);
        $result = $connection->fetchRow('SELECT @ONE, @TWO, @THREE, @FOUR, @FIVE;');
        return array_values($result);
    }
    protected function _initItems()
    {   
        $data  = $this->_getItemsData();

        $items = array();
        foreach ($data as $itemData) {
            $item = $this->_createItem(
                $itemData['label'],
                $itemData['value'],
                $itemData['count']
            );
            $item->setOptionId($itemData['option_id']);
            $items[] = $item;
        }
        $this->_items = $items;

        return $this;
    }

    protected function getLabelHtml($countStars)
    {
         $html = '
</div>'; return $html; } } ?>

enter image description here


Get this bounty!!!

#StackBounty: #magento2 #product #programmatically #duplicate #create-product Magento 2 : Error while adding product programatically On…

Bounty: 50

I am trying to add product programmatically on catalog_product_save_after observer.

Basically what i try to achieve is create a Duplicate Sample product of current product if PRODUCT-SKU-sample does not exist otherwise Update the price of PRODUCT-SKU-sample Sample product.

File : Namespace/Modulename/Observer/Catalog/ProductSaveAfter.php

$_product = $observer->getProduct();
$isSampleOrderEnabled = $observer->getProduct()->getData('enable_sample_order');

if($isSampleOrderEnabled == 1){

    $objectManager = MagentoFrameworkAppObjectManager::getInstance();
    $store = $objectManager->get('MagentoStoreModelStoreManagerInterface')->getStore();
    $_mediapath = BP.'/pub/media/'. 'catalog/product' . $_product->getImage();
    $imageUrl  =  $store->getBaseDir(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA).'catalog/product' . $_product->getImage();

    $getProduct = $objectManager->get('MagentoCatalogModelProduct');
    $sampleSkuExists = $getProduct->getIdBySku($_product->getSku().'-sample');

    $sampleProductPrice = $observer->getProduct()->getData('sample_price');
    if($sampleSkuExists == FALSE) {

        $product = $objectManager->create('MagentoCatalogModelProduct');
        try {
            $product->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
                    ->setAttributeSetId($_product->getAttributeSetId()) //ID of a attribute set named 'default'
                    ->setTypeId('simple') 
                    ->setCreatedAt(strtotime('now')) 
                    ->setSku($_product->getSku().'-sample') //SKU
                    ->setName($_product->getName()."-sample")
                    ->setWeight(4.0000)
                    ->setStatus(1) 
                    ->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
                    ->setVisibility(1) 
                    ->setPrice($sampleProductPrice) 
                    ->setMetaTitle($_product->getMetaTitle())
                    ->setMetaKeyword($_product->getMetaKeyword())
                    ->setMetaDescription($_product->getMetaDescription())
                    ->setDescription($_product->getDescription())
                    ->setShortDescription($_product->getShortDescription())
                    ->setStockData(
                        array(
                           'use_config_manage_stock' => 0, //'Use config settings' checkbox
                           'manage_stock'=>1, //manage stock
                           'min_sale_qty'=>1, //Minimum Qty Allowed in Shopping Cart
                           'max_sale_qty'=>2, //Maximum Qty Allowed in Shopping Cart
                           'is_in_stock' => 1, //Stock Availability
                           'qty' => 99999//qty
                        )
                    );

            echo "BEFORE SAVING THE NEW PRODUCT";
            $res = $product->save();
            echo "AFTER SAVING THE NEW PRODUCT";

            var_dump($res); 
            echo $product->getEntityId();
            // Save the new Sample Product ID to original product Attribute. 
        } catch (Exception $e ) {
            echo    $e->getMessage();
        }
    } else {
        echo "UPDATE CODE GOES HERE";
    }
}

I cant get past $product->save();. Code execution stop right there without any notice/error.

Checked all the log files. there is no relevent information there as well.


Get this bounty!!!

#StackBounty: #magento2 #event-observer #stock #plugin Cannot create plugin for stock resource model's correctItemsQty

Bounty: 300

I want to be able to observe any product’s stock changing in any way, without having to do so with database triggers.

In Magento 1.x the lowest level I could find that does this consistently is the Stock Item’s resource model correctItemsQty method that actually writes product quantities to the database.

In Magento 2.x, I’ve tried to create a plugin for MagentoCatalogInventoryModelResourceModelStock::correctItemsQty in the form of MyPlugin::afterCorrectItemsQty. The configuration for the plugin is pretty standard:

<type name="MagentoCatalogInventoryModelResourceModelStock">
    <plugin name="my_stock_item_plugin"
        type="MyCompanyPluginStockPlugin"
        sortOrder="100" />
</type>

My method just for testing just has a die('plugged in') in it.

After setup:di:compile and clearing cache, this doesn’t run when I place an order in the frontend or admin, ship an order, credit memo an order etc. (In Magento 1.x this method does fire).

To eliminate my plugin being the problem I added my die call into the top of the core method in the core magento-catalog-inventory module, but it’s still not executing.

Am I missing something here? Has there been a behavioural change that means that this method doesn’t get called when you place an order (for example)?

Aside from that, is there a better way that I can observe all product stock changes in Magento 2?

Disclaimer: I’ve seen this question and this core bug. This code is for a module, so I don’t have the liberty to wait for the core fix to be released, or monkey patch it in. I’ve also checked from my docker container that my changes are syncing through (they are) to ensure it’s not a local filesync problem.


Get this bounty!!!

#StackBounty: #magento2 #event-observer #stock #plugin Cannot create plugin for stock resource model's correctItemsQty

Bounty: 300

I want to be able to observe any product’s stock changing in any way, without having to do so with database triggers.

In Magento 1.x the lowest level I could find that does this consistently is the Stock Item’s resource model correctItemsQty method that actually writes product quantities to the database.

In Magento 2.x, I’ve tried to create a plugin for MagentoCatalogInventoryModelResourceModelStock::correctItemsQty in the form of MyPlugin::afterCorrectItemsQty. The configuration for the plugin is pretty standard:

<type name="MagentoCatalogInventoryModelResourceModelStock">
    <plugin name="my_stock_item_plugin"
        type="MyCompanyPluginStockPlugin"
        sortOrder="100" />
</type>

My method just for testing just has a die('plugged in') in it.

After setup:di:compile and clearing cache, this doesn’t run when I place an order in the frontend or admin, ship an order, credit memo an order etc. (In Magento 1.x this method does fire).

To eliminate my plugin being the problem I added my die call into the top of the core method in the core magento-catalog-inventory module, but it’s still not executing.

Am I missing something here? Has there been a behavioural change that means that this method doesn’t get called when you place an order (for example)?

Aside from that, is there a better way that I can observe all product stock changes in Magento 2?

Disclaimer: I’ve seen this question and this core bug. This code is for a module, so I don’t have the liberty to wait for the core fix to be released, or monkey patch it in. I’ve also checked from my docker container that my changes are syncing through (they are) to ensure it’s not a local filesync problem.


Get this bounty!!!

#StackBounty: #magento2 #event-observer #stock #plugin Cannot create plugin for stock resource model's correctItemsQty

Bounty: 300

I want to be able to observe any product’s stock changing in any way, without having to do so with database triggers.

In Magento 1.x the lowest level I could find that does this consistently is the Stock Item’s resource model correctItemsQty method that actually writes product quantities to the database.

In Magento 2.x, I’ve tried to create a plugin for MagentoCatalogInventoryModelResourceModelStock::correctItemsQty in the form of MyPlugin::afterCorrectItemsQty. The configuration for the plugin is pretty standard:

<type name="MagentoCatalogInventoryModelResourceModelStock">
    <plugin name="my_stock_item_plugin"
        type="MyCompanyPluginStockPlugin"
        sortOrder="100" />
</type>

My method just for testing just has a die('plugged in') in it.

After setup:di:compile and clearing cache, this doesn’t run when I place an order in the frontend or admin, ship an order, credit memo an order etc. (In Magento 1.x this method does fire).

To eliminate my plugin being the problem I added my die call into the top of the core method in the core magento-catalog-inventory module, but it’s still not executing.

Am I missing something here? Has there been a behavioural change that means that this method doesn’t get called when you place an order (for example)?

Aside from that, is there a better way that I can observe all product stock changes in Magento 2?

Disclaimer: I’ve seen this question and this core bug. This code is for a module, so I don’t have the liberty to wait for the core fix to be released, or monkey patch it in. I’ve also checked from my docker container that my changes are syncing through (they are) to ensure it’s not a local filesync problem.


Get this bounty!!!

#StackBounty: #magento2 #event-observer #stock #plugin Cannot create plugin for stock resource model's correctItemsQty

Bounty: 300

I want to be able to observe any product’s stock changing in any way, without having to do so with database triggers.

In Magento 1.x the lowest level I could find that does this consistently is the Stock Item’s resource model correctItemsQty method that actually writes product quantities to the database.

In Magento 2.x, I’ve tried to create a plugin for MagentoCatalogInventoryModelResourceModelStock::correctItemsQty in the form of MyPlugin::afterCorrectItemsQty. The configuration for the plugin is pretty standard:

<type name="MagentoCatalogInventoryModelResourceModelStock">
    <plugin name="my_stock_item_plugin"
        type="MyCompanyPluginStockPlugin"
        sortOrder="100" />
</type>

My method just for testing just has a die('plugged in') in it.

After setup:di:compile and clearing cache, this doesn’t run when I place an order in the frontend or admin, ship an order, credit memo an order etc. (In Magento 1.x this method does fire).

To eliminate my plugin being the problem I added my die call into the top of the core method in the core magento-catalog-inventory module, but it’s still not executing.

Am I missing something here? Has there been a behavioural change that means that this method doesn’t get called when you place an order (for example)?

Aside from that, is there a better way that I can observe all product stock changes in Magento 2?

Disclaimer: I’ve seen this question and this core bug. This code is for a module, so I don’t have the liberty to wait for the core fix to be released, or monkey patch it in. I’ve also checked from my docker container that my changes are syncing through (they are) to ensure it’s not a local filesync problem.


Get this bounty!!!

#StackBounty: #magento2 Magento 2 catalog_product_get_final_price event not working for configurable product

Bounty: 50

I have to set the product price to a custom value depends up on the customer. So I have written an event catalog_product_get_final_price and in the observer I have set the custom price for the product. But this is working only for “Simple Product” (visibility both). When I view the configurable product nothing is happened. Even I have write a die() in the observer and it is working when I view the Simple product but not for the configurable product. That means when I view the configurable product, the event is not triggering.

How can I set the simple product’s price to a custom value using event? I need this for the “listing” and “view page”


Get this bounty!!!