1

I want to add multiple products to quote, but its adding only 1st product. I have used \Magento\Quote\Model\QuoteFactory for creating quote.

foreach ($items as $item) {
    $product = $this->product->loadByAttribute('sku', $item['sku']);
    if (!is_object($product)) {
        //If product not avilable then display error message
        echo(__(' Material with code ' . $item['sku'] . ' does not exist!' . '<br/>'));
        continue;
    }
    $product = $this->product->load($product->getId());
    $productStock = $this->_stockItemRepository->get($product->getId());
    if (!$productStock->getIsInStock()) {
        //If product out of stock then display error message
        echo(__(' Material with code ' . $item['sku'] . ' is out of stock!' . '<br/>'));
        continue;
    }
    //check for porduct quantity
    if ($productStock->getQty() < $item['confirmedQuantity']) {
        echo(__(' Material code ' . $item['sku'] . ' does not have ordered quantity!' . '<br/>'));
        continue;
    }
    $product->setPrice($item['grossPrice']);
    $quote->addProduct($product, null);
    $quote->setCreatedAt($this->getDate($item['purchaseOrderDate']));
    echo $item['sku'] . "==";
}
//check quote item count
echo count($quote->getAllVisibleItems());

Quote count always print 1; there are 5 products in item array; output for item['sku']:

24-MB01==24-MB02==24-MB03==24-MB04==24-MB05==

but its always adding 1st product to quote. I have also checked in database.

1
  • accept the answer If you find it helpful so it helps other community members :)
    – Keyur Shah
    Dec 20, 2016 at 9:10

1 Answer 1

3

It create an issue because,you have used this in your constructor

protected $_product;

    public function __construct(\Magento\Catalog\Model\Product $_product 
    ) {
        $this->_product = $product;        
    }

Instead of this use below code constructor injection

public function __construct(\Magento\Catalog\Model\ProductFactory $_product 
    ) {
        $this->_product = $product;        
    }    

And replace

$product = $this->product->load($product->getId());

with this

$product = $this->_product->create()->load($product->getId())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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