1

In my test I am creating a product like this:

$product = $this->objectManagerHelper->create('Magento\Catalog\Model\Product');
$product
    ->setId(1)
    ->setTypeId(Product\Type::TYPE_SIMPLE)
    ->setWebsiteIds([1])
    ->setName('Simple Product 1')
    ->setSku('simple1')
    ->setPrice(10)
    ->setVisibility(Product\Visibility::VISIBILITY_BOTH)
    ->setUrlKey('url-key2')
    ->setCategoryIds([2])
    ->setStockData([
        'use_config_manage_stock' => $manageStock,
        'qty' => $qty,
        'is_qty_decimal' => 0,
        'is_in_stock' => $isInStock
    ])
    ->setData('erp_procurement', $erpProcurement)
    ->setData('qty', $qty)
    ->setData('manage_stock', $manageStock)
    ->setData('stock_lead_time', $stockLeadTime)
    ->setData(Product::STATUS, $stockstatus)
    ->save();

But how can I have the product as if it is loaded in listing only with the attributes that have used_in_product_listing set to true?

1

From here I found the method getAttributesUsedInListing() in \Magento\Catalog\Model\ResourceModel\Config. The idea from Alex was a good hint.

  1. Creating a collection
  2. Filtering by the product id
  3. Adding attributes from getAttributesUsedInListing() to the select

solved the problem.

Here my code:

$productCollection = $this->productCollectionFactory->create();
$productCollection->addIdFilter($product->getId());
$productCollection->addAttributeToSelect($this->getAttributesUsedInListing());
$product = $productCollection->getFirstItem();

private function getAttributesUsedInListing()
{
    $attributeCodes = [];
    $attributes = $this->config->getAttributesUsedInListing();

    array_walk_recursive($attributes, function ($value, $key) use (&$attributeCodes) {
        if ($key == 'attribute_code') {
            $attributeCodes[] = $value;
        }
    });
    return $attributeCodes;
}

I used $this->getAttributesUsedInListing() to create an array with only the attribute codes in the array to pass it to addAttributeToSelect().

0

This should also work

/** @var \Magento\Catalog\Model\Config */
protected $config;

...

$attributes = array_keys($this->config->getAttributesUsedInProductListing());

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.