1
public function createCollection()
{
    /** @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
    $collection = $this->productCollectionFactory->create();
    if ($this->getData('store_id') !== null) {
        $collection->setStoreId($this->getData('store_id'));
    }

    $collection->setVisibility($this->catalogProductVisibility->getVisibleInCatalogIds());

    $collection = $this->_addProductAttributesAndPrices($collection)
        ->addStoreFilter()
        ->addAttributeToSort('created_at', 'desc')
        ->setPageSize($this->getPageSize())
        ->setCurPage($this->getRequest()->getParam($this->getData('page_var_name'), 1));

    $conditions = $this->getConditions();
    $conditions->collectValidatedAttributes($collection);
    $this->sqlBuilder->attachConditionToCollection($collection, $conditions);

    /**
     * Prevent retrieval of duplicate records. This may occur when multiselect product attribute matches
     * several allowed values from condition simultaneously
     */
    $collection->distinct(true);

    return $collection;
}

/**
 * Get conditions
 *
 * @return \Magento\Rule\Model\Condition\Combine
 */
protected function getConditions()
{
    $conditions = $this->getData('conditions_encoded')
        ? $this->getData('conditions_encoded')
        : $this->getData('conditions');

    if ($conditions) {
        $conditions = $this->conditionsHelper->decode($conditions);
    }

    foreach ($conditions as $key => $condition) {
        if (!empty($condition['attribute'])
            && in_array($condition['attribute'], ['special_from_date', 'special_to_date'])
        ) {
            $conditions[$key]['value'] = date('Y-m-d H:i:s', strtotime($condition['value']));
        }
    }

    $this->rule->loadPost(['conditions' => $conditions]);
    return $this->rule->getConditions();
}

I found solution in core magento/catalogwidget/block/product. How do I filter product list follow condition in custom module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.