#StackBounty: #magento-2.1 #custom #product-collection #render Magento 2 – Render custom product collection via list.phtml

Bounty: 50

The product grid of a category page (frontend) is rendered via instructions in catalog_category_view.xml. Lets say I have a custon product collection (which I got via ProductRepositoryInterface::getList($searchCriteria) method) in a custom block class and want to render this collection. The rendered result should be displayed as a product grid on frontend (just like any category page).

How can this be done ?

By looking into catalog_category_view.xml there are two significant lines, which are responsible for rendering a product collection:

            <block class="MagentoCatalogBlockCategoryView" name="category.products" template="Magento_Catalog::category/products.phtml">
            <block class="MagentoCatalogBlockProductListProduct" name="category.products.list" as="product_list" template="Magento_Catalog::product/list.phtml">

How can I provide my custom product collection to these template files, so they render my collection ?

Correct me, if I am wrong on this


Get this bounty!!!

#StackBounty: #magento-2.1 #magento-community Stock inconsistency – Magento 2

Bounty: 100

It seems system product stock and real stock are not in-sync.We have matched real stock and product stocks on System several times, still it gets differ after some period of time (weeks/days) it’s just matter of time.

I know this is a silly question. I don’t know how to reproduce this but we experience this issue for a long time. What do I need to know, what could be the possible reason for this? What can I do to prevent this? Is this is a known bug?

I’m using Magento 2.1.


Get this bounty!!!

#StackBounty: #magento-2.1 #price #import #csv #reindex Importing prices csv is taking a long time

Bounty: 50

In Magento 2, there are roughly 115,000 products in the store. There are 7 customer groups. When importing prices via csv, the batch upload slowly imports the price but eventually crawls to a stop. I’ve checked all error logs in my server, can’t find any failure notices in magento logs, or any other server logs. No email is sent.

More details on the setup:

  • RHEL 7
  • PHP 7
  • Apache
  • MySQL
  • Magento 2.1 EE

How I setup up the import is through a scheduled task, and hitting ‘run’. I’ve tried batches of 50000, 10000, 5000, 1000. All have the same effect. When uploading products, customers, and availability – Magento had no issue with big bulk uploading.

Another symptom I may be seeing is bin/magento indexer:reindex takes no more than :30 seconds for each category, except for Prices and EAV. It takes over 3 minutes each. Currently there only 3000 prices in the database, so 3 minutes to reindex seems like a lot.

Has anyone come across this? Any suggested fixes?


Get this bounty!!!

#StackBounty: #magento-2.1 Images does not load on first load

Bounty: 50

When I enter my Magento website, Most of the time, some images do not load
(Sometimes they do load).

However, when I refresh the page, all the images become visible.

Please suggest how can I debug this Problem?


Get this bounty!!!

#StackBounty: #magento-2.1 #plugin #tierprice How to create around Plugin for the getSavePercent method of the MagentoCatalogPricing…

Bounty: 50

I have used following code to create around plugin for the getSavePercent method of MagentoCatalogPricingPriceTierPrice class.
(My objective is to get two decimals precision.)

<?php

namespace MymoduleCommonPlugin;

use MagentoFrameworkPricingAmountAmountInterface;
use MagentoFrameworkPricingSaleableInterface;
use MagentoCatalogPricingPriceFinalPrice;

class TierPricePlugin
{
    /**
     * @var MagentoFrameworkAppConfigScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var PriceInfoInterface
     */
    protected $priceInfo;

    public function __construct(
        MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
        SaleableInterface $saleableItem
   ) {
      $this->scopeConfig = $scopeConfig;
      $this->priceInfo = $saleableItem->getPriceInfo();
   }

    /**
     * @param AmountInterface $amount
     * @return float
     */
    public function aroundGetSavePercent(MagentoCatalogPricingPriceTierPrice $subject, Closure $proceed, $amount)
    {
        $precision = $this->scopeConfig->getValue('mymodule_common/tier_prices/precision', MagentoStoreModelScopeInterface::SCOPE_STORE);

        return round(
            100 - ((100 / $this->priceInfo->getPrice(FinalPrice::PRICE_CODE)->getValue())
                * $amount->getBaseAmount()),$precision
        );
    }
}

I get following error.

PHP Fatal error: 
 Uncaught Error: Cannot instantiate interface Magento\Framework\Pricing\SaleableInterface in /var/www/html/Mysite/vendor/magento/framework/ObjectManager/Factory/Dynamic/Developer.php:73nStack trace:n#0
 /var/www/html/Mysite/vendor/magento/framework/ObjectManager/ObjectManager.php(71): Magento\Framework\ObjectManager\Factory\Dynamic\Developer->create('Magento\\Framewo...')n#1
 /var/www/html/Mysite/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php(126): Magento\Framework\ObjectManager\ObjectManager->get('Magento\\Framewo...')n#2 
 /var/www/html/Mysite/vendor/magento/framework/ObjectManager/Factory/Dynamic/Developer.php(53): Magento\Framework\ObjectManager\Factory\AbstractFactory->resolveArgument(Array, 'Magento\\Framewo...', NULL, 'saleableItem', 'Mymodule\\Common\\P...')n#3
 /var/www/html/Mysite/vendor/magento/framework/ObjectManager/Factory/Dynamic/Developer.php(82): Magento\Framework\ObjectManager\Factory\Dynamic\Developer->_resolveArguments('Mymodule\\Common\\P...', Array, Array)n#4 
 /var/www/html/Mysite/vendor/m in /var/www/html/Mysite/vendor/magento/framework/ObjectManager/Factory/Dynamic/Developer.php

Issue seems to be created by following code line

 $this->priceInfo->getPrice(FinalPrice::PRICE_CODE)->getValue()

I want to get the final price of the product in my plugin code, so i am using above mentioned line. But there seems to be problem with $this->priceInfo


Get this bounty!!!

#StackBounty: #magento-2.1 How do I create a configurable product programmatically and assign simple products?

Bounty: 50

I am trying to create some simple products, then have those simple products assigned to a configurable product programmatically. But no matter what I try, it seems to not associate them. What am I doing wrong?

Here is what I have so far. I have commented out all the attempts I have tried too so you can see what I’ve tried already:

namespace CompanyModuleControllerGet;

use Magento;
use CompanyModuleHelperHelper;

class OutboundItem extends MagentoFrameworkAppActionAction
{
    protected $storeManager;
    protected $productFactory;
    protected $indexerFactory;
    public $helper;

    public function __construct(
        MagentoFrameworkAppActionContext $context,
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoCatalogModelProductFactory $productFactory,
        MagentoIndexerModelIndexerFactory $indexerFactory,
        Helper $helper
    )
    {
        $this->storeManager = $storeManager;
        $this->productFactory = $productFactory;
        $this->indexerFactory = $indexerFactory;
        $this->helper = $helper;
        return parent::__construct($context);
    }

    public function execute()
    {
        // Get Website ID
        $websiteId = $this->storeManager->getWebsite()->getWebsiteId();
        $storeId = $this->storeManager->getDefaultStoreView()->getId();

        // Get the the list of products that need importing from the document.
        $items = $this->helper->getItems();

        // Loop through all the results.
        foreach ($items as $item) {
            try {
                // Create common product info variables.
                $product_name = $item->ProdName;
                $price = $item->UnitPrice;
                $weight = $item->NetWeight;
                $categoryIds = [2, $this->helper->getCategoryIdByName(substr($product_name, 0, 1))];

                // Create variable to store the created variant ids.
                $variant_ids = array();

//                $prodData = array();
                // Loop through the variants.
                foreach ($item->variants as $variant) {
                    $product = $this->productFactory->create();

                    // Preparing data for new customer.
                    $product->setSku($product_name . '_' . $variant->Code);
                    $product->setName($variant->Description); // Name of Product
                    $product->setAttributeSetId($product->getDefaultAttributeSetId()); // Attribute set id
                    $product->setStatus(1); // Status on product enabled/ disabled 1/0
                    $product->setWeight($weight); // weight of product
                    $product->setVisibility(MagentoCatalogModelProductVisibility::VISIBILITY_NOT_VISIBLE); // visibilty of product (catalog / search / catalog, search / Not visible individually)
                    $product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
                    $product->setPrice($variant->SalesPrice); // price of product
                    $product->setStockData(
                        array(
                            'use_config_manage_stock' => 0,
                            'manage_stock' => 1,
                            'is_in_stock' => 1,
                            'qty' => $variant->AvailableQuantity
                        )
                    );

                    $product->setWebsiteIds(array($websiteId));
                    $product->setCategoryIds($categoryIds);
                    $product->setStoreId($storeId);

                    $colour = $variant->value2;
                    $colourId = $this->helper->createOrGetId('color', $colour);
                    $product->setColor($colourId);

                    $size = $variant->value1;
                    $sizeId = $this->helper->createOrGetId('size', $size);
                    $product->setSize($sizeId);

                    // Save data.
                    $product->save();

                    if ($product->getId() > 0) {
                        $variant_ids[] = $product->getId();
//                        $prodData[$product->getId()] = array(
//                            '0' => array(
//                                'label' => 'Size',
//                                'attribute_id' => $this->helper->getAttribute('size')->getAttributeId(),
//                                'value_index' => $sizeId
//                            ),
//                            '1' => array(
//                                'label' => 'Color',
//                                'attribute_id' => $this->helper->getAttribute('color')->getAttributeId(),
//                                'value_index' => $colourId
//                            )
//                        );
                    }

                    $prodConfAttr = $product->getExtensionAttributes();
                    $prodConfAttr->setConfigurableProductLinks($variant_ids);
                    $product->setExtensionAttributes($prodConfAttr);
                }

                // Instantiate magento customer object.
                $product = $this->productFactory->create();

                // Preparing data for new customer.
                $product->setTypeId('configurable'); // type of product (simple/virtual/downloadable/configurable)
                $product->setSku($product_name);
                $product->setName($product_name); // Name of Product
                $product->setAttributeSetId($product->getDefaultAttributeSetId()); // Attribute set id
                $product->setStatus(1); // Status on product enabled/ disabled 1/0
                $product->setWeight($weight); // weight of product
                $product->setVisibility(MagentoCatalogModelProductVisibility::VISIBILITY_BOTH); // visibilty of product (catalog / search / catalog, search / Not visible individually)
                $product->setPrice($price); // price of product
                $product->setStockData(
                    array(
                        'use_config_manage_stock' => 0,
                        'manage_stock' => 1,
                        'is_in_stock' => 1
                    )
                );
                //setCategoryId?
                $product->setWebsiteIds(array($websiteId));
                $product->setCategoryIds($categoryIds);
                $product->setStoreId($storeId);

                // Set variants
//                $product->setNewVariationsAttributeSetId($product->getDefaultAttributeSetId());
//                $product->setAssociatedProductIds($variant_ids);
//                $product->setAffectConfigurableProductAttributes(4);
//
//                $product->getTypeInstance()->setUsedProductAttributeIds(array(
//                    $this->helper->getAttribute('color')->getAttributeId(),
//                    $this->helper->getAttribute('size')->getAttributeId()
//                ), $product);
//                $attData = $product->getTypeInstance()->getConfigurableAttributesAsArray();
//                $product->setCanSaveConfigurableAttributes(true);
//                $product->setConfigurableAttributesData($attData, $product);
////                $prodData = array();
////                foreach($variant_ids as $key => $id) {
////                    $prodData[$id] = array(
////                        '0' => array(
////                            'label'
////                        )
////                    );
////                }
//                $product->setConfigurableProductsData($prodData);

//                unset($variant_ids);

                // Save data.
                $product->save();

                echo $this->helper->getPrint($variant_ids);
                echo $this->helper->getPrint($categoryIds);
                echo $this->helper->getPrint($storeId);
                echo $this->helper->getPrint($item);
            } catch (Exception $e) {
                echo $this->helper->getPrint($item);
                echo $this->helper->getPrint($e->getMessage());
            }
        }

        echo $this->helper->getPrint('Import Complete.');

        exit;
    }
}


Get this bounty!!!

#StackBounty: #magento2 #magento-2.1 How do I create a configurable product programmatically and assign simple products?

Bounty: 50

I am trying to create some simple products, then have those simple products assigned to a configurable product programmatically. But no matter what I try, it seems to not associate them. What am I doing wrong?

Here is what I have so far. I have commented out all the attempts I have tried too so you can see what I’ve tried already:

namespace CompanyModuleControllerGet;

use Magento;
use CompanyModuleHelperHelper;

class OutboundItem extends MagentoFrameworkAppActionAction
{
    protected $storeManager;
    protected $productFactory;
    protected $indexerFactory;
    public $helper;

    public function __construct(
        MagentoFrameworkAppActionContext $context,
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoCatalogModelProductFactory $productFactory,
        MagentoIndexerModelIndexerFactory $indexerFactory,
        Helper $helper
    )
    {
        $this->storeManager = $storeManager;
        $this->productFactory = $productFactory;
        $this->indexerFactory = $indexerFactory;
        $this->helper = $helper;
        return parent::__construct($context);
    }

    public function execute()
    {
        // Get Website ID
        $websiteId = $this->storeManager->getWebsite()->getWebsiteId();
        $storeId = $this->storeManager->getDefaultStoreView()->getId();

        // Get the the list of products that need importing from the document.
        $items = $this->helper->getItems();

        // Loop through all the results.
        foreach ($items as $item) {
            try {
                // Create common product info variables.
                $product_name = $item->ProdName;
                $price = $item->UnitPrice;
                $weight = $item->NetWeight;
                $categoryIds = [2, $this->helper->getCategoryIdByName(substr($product_name, 0, 1))];

                // Create variable to store the created variant ids.
                $variant_ids = array();

//                $prodData = array();
                // Loop through the variants.
                foreach ($item->variants as $variant) {
                    $product = $this->productFactory->create();

                    // Preparing data for new customer.
                    $product->setSku($product_name . '_' . $variant->Code);
                    $product->setName($variant->Description); // Name of Product
                    $product->setAttributeSetId($product->getDefaultAttributeSetId()); // Attribute set id
                    $product->setStatus(1); // Status on product enabled/ disabled 1/0
                    $product->setWeight($weight); // weight of product
                    $product->setVisibility(MagentoCatalogModelProductVisibility::VISIBILITY_NOT_VISIBLE); // visibilty of product (catalog / search / catalog, search / Not visible individually)
                    $product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
                    $product->setPrice($variant->SalesPrice); // price of product
                    $product->setStockData(
                        array(
                            'use_config_manage_stock' => 0,
                            'manage_stock' => 1,
                            'is_in_stock' => 1,
                            'qty' => $variant->AvailableQuantity
                        )
                    );

                    $product->setWebsiteIds(array($websiteId));
                    $product->setCategoryIds($categoryIds);
                    $product->setStoreId($storeId);

                    $colour = $variant->value2;
                    $colourId = $this->helper->createOrGetId('color', $colour);
                    $product->setColor($colourId);

                    $size = $variant->value1;
                    $sizeId = $this->helper->createOrGetId('size', $size);
                    $product->setSize($sizeId);

                    // Save data.
                    $product->save();

                    if ($product->getId() > 0) {
                        $variant_ids[] = $product->getId();
//                        $prodData[$product->getId()] = array(
//                            '0' => array(
//                                'label' => 'Size',
//                                'attribute_id' => $this->helper->getAttribute('size')->getAttributeId(),
//                                'value_index' => $sizeId
//                            ),
//                            '1' => array(
//                                'label' => 'Color',
//                                'attribute_id' => $this->helper->getAttribute('color')->getAttributeId(),
//                                'value_index' => $colourId
//                            )
//                        );
                    }

                    $prodConfAttr = $product->getExtensionAttributes();
                    $prodConfAttr->setConfigurableProductLinks($variant_ids);
                    $product->setExtensionAttributes($prodConfAttr);
                }

                // Instantiate magento customer object.
                $product = $this->productFactory->create();

                // Preparing data for new customer.
                $product->setTypeId('configurable'); // type of product (simple/virtual/downloadable/configurable)
                $product->setSku($product_name);
                $product->setName($product_name); // Name of Product
                $product->setAttributeSetId($product->getDefaultAttributeSetId()); // Attribute set id
                $product->setStatus(1); // Status on product enabled/ disabled 1/0
                $product->setWeight($weight); // weight of product
                $product->setVisibility(MagentoCatalogModelProductVisibility::VISIBILITY_BOTH); // visibilty of product (catalog / search / catalog, search / Not visible individually)
                $product->setPrice($price); // price of product
                $product->setStockData(
                    array(
                        'use_config_manage_stock' => 0,
                        'manage_stock' => 1,
                        'is_in_stock' => 1
                    )
                );
                //setCategoryId?
                $product->setWebsiteIds(array($websiteId));
                $product->setCategoryIds($categoryIds);
                $product->setStoreId($storeId);

                // Set variants
//                $product->setNewVariationsAttributeSetId($product->getDefaultAttributeSetId());
//                $product->setAssociatedProductIds($variant_ids);
//                $product->setAffectConfigurableProductAttributes(4);
//
//                $product->getTypeInstance()->setUsedProductAttributeIds(array(
//                    $this->helper->getAttribute('color')->getAttributeId(),
//                    $this->helper->getAttribute('size')->getAttributeId()
//                ), $product);
//                $attData = $product->getTypeInstance()->getConfigurableAttributesAsArray();
//                $product->setCanSaveConfigurableAttributes(true);
//                $product->setConfigurableAttributesData($attData, $product);
////                $prodData = array();
////                foreach($variant_ids as $key => $id) {
////                    $prodData[$id] = array(
////                        '0' => array(
////                            'label'
////                        )
////                    );
////                }
//                $product->setConfigurableProductsData($prodData);

//                unset($variant_ids);

                // Save data.
                $product->save();

                echo $this->helper->getPrint($variant_ids);
                echo $this->helper->getPrint($categoryIds);
                echo $this->helper->getPrint($storeId);
                echo $this->helper->getPrint($item);
            } catch (Exception $e) {
                echo $this->helper->getPrint($item);
                echo $this->helper->getPrint($e->getMessage());
            }
        }

        echo $this->helper->getPrint('Import Complete.');

        exit;
    }
}


Get this bounty!!!

#StackBounty: #magento-2.1 #overrides #tierprice #resource-model Magento2 Override Resource Model does not Work

Bounty: 50

I am trying to override a resource model class MagentoCatalogModelResourceModelProductAttributeBackendTierPrice to select new columns that I have created in the catalog_product_entity_tier_price table.
However, the new columns are not selected and the model is not getting overridden.

namespace [vendor][module]ModelResourceModelProductAttributeBackend;

class TierPrice extends MagentoCatalogModelResourceModelProductAttributeBackendTierPrice
{

    /**
     * Add qty column
     *
     * @param array $columns
     * @return array
     */
    protected function _loadPriceDataColumns($columns)
    {
        $columns = parent::_loadPriceDataColumns($columns);
        //$columns['price_qty'] = 'qty';
        //new columns
        $columns['created_by']='created_by';
        $columns['price_effective_from']='price_effective_from';
        $columns['price_effective_to']='price_effective_to';
        $columns['deletion_flag']='deletion_flag';
        return $columns;

    }
}

di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLcation="urn:magento:framework:ObjectManager/etc/config.xsd">
   <preference for="MagentoCatalogModelResourceModelProductAttributeBackendTierPrice" type="[vendor][module]ModelResourceModelProductAttributeBackendTierPrice" /> 
</config>

script.php

 $p=$productRepo->get('s1');
    echo $p->getName();
    $tier=$p->getTierPrices();
    foreach($tier as $t)
    {
     print_r($t->getData());
    }

returns error Notice: Undefined index: created_by

How to override this class to add additional columns of the tier price table.

Note
I have implemented interface for the new columns. So if I directly edit the core resource model, it works.


Get this bounty!!!

#StackBounty: #magento2 #magento-2.1 #category #save Category with 20000 product not save

Bounty: 50

I have a category with 20000 products and 50 subcategories, while I tried to save that category at that time Magento go into infinite loop and after 10-15 min getting 500 error.

I have set 18000 max time out and 100000 max input vars.
Also in front end category page showing empty and in HTML body shown as empty

https://drive.google.com/file/d/0B_qaQlQ9Qh8XeUVQRlFjQ0Q4QXM/view?usp=drivesdk.

Can anyone help me to resolve this issue?
Magento version 2.1.6


Get this bounty!!!

#StackBounty: #magento-2.1 #product #collection #custom-options AND condition in addAttributeToFilter not giving desired result

Bounty: 50

According to answer to this related question
the AND condition in addAttributeToFilter is added by adding consecutive addAttributeToFilter so my statement is something like;

$_productCollection->addAttributeToSelect('*')->addAttributeToFilter('manufacturer', array(
                    array('nin' => $brands)
                ))->addAttributeToFilter('warehouse1', array(
                    array('nin' => 0)
                ))->addAttributeToFilter('warehouse4', array(
                    array('nin' => 0)
                )); // I want product to be excluded when both warehouse1 and warehouse4 is 0

As in the code above I need the product to be removed from collection when both “warehouse1” and “warehouse4” are simultaneously 0 but instead the code is first filtering collection based on “warehouse1” and then the filtered collection is filtered again for “warehouse4”.
As a result I am also excluding products which have 0 for “warehouse1” but not a 0 for “warehouse4”.
Please help me resolve this.


Get this bounty!!!