Erlaunis
Erlaunis

Reputation: 1451

Add stock data on product programatically in Magento 2

I want to add stock data on a product but it doesn't work. In my function, I have a product created by :

$product = $objectManager->create('Magento\Catalog\Model\Product');

Then, I set some data like price, status, name, ... And eventually, I add a code for the stock :

$product->setStockData(array(
                'use_config_manage_stock' => (bool)0, //'Use config settings' checkbox
                'manage_stock' => (bool)1, //manage stock
                'min_sale_qty' => 0, //Minimum Qty Allowed in Shopping Cart
                'max_sale_qty' => 0, //Maximum Qty Allowed in Shopping Cart
                'is_in_stock' => (bool)1, //Stock Availability
                'qty' => 0 //qty
                )
            );

I don't want that the product inherit the config settings and I absolutly want a quantity different of null (0 or greater).

But, when the function is launched, the product is created, every data is ok exept the stock data.

enter image description here

Upvotes: 1

Views: 3182

Answers (3)

Rakesh Donga
Rakesh Donga

Reputation: 135

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

public function updateQty(){
    $sku = '24-mb01';
    $product = $this->productFactory->create();
    $productId = $product->getIdBySku($sku);
    if($productId){
        $product->load($productId);
    }

    $product->setStockData(
        array(
            'use_config_manage_stock' => 0,
            'manage_stock' => 1,
            'is_in_stock' => 1,
            'qty' => 10
        )
    );

    try {
        $product->save(); 
        echo $sku.' updated. '; 
    } catch (Exception $e) {
        echo $e->getException();
    }
}

Upvotes: 0

Karimeri
Karimeri

Reputation: 65

try this code below , it works for me

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

       public function updateQty(){
       $sku = 'xxxxxxxxx';
       $product = $this->productFactory->create();
       $productId = $product->getIdBySku($sku);
      if($productId){
      $product->load($productId);
      }
       $product->setStockData(
    array(
        'use_config_manage_stock' => 0,
        'manage_stock' => 1,
        'is_in_stock' => 1,
        'qty' => 10
       )
      );

     $product->save(); 
     }

Upvotes: 1

Karimeri
Karimeri

Reputation: 65

Can you check please in the Backend system setting if the attribute "manage stock" is set to Yes, this is the path : stores => configuration => Catalog => Stock => manage Stock

Upvotes: 0

Related Questions