skip to Main Content

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('MagentoCatalogModelProduct');

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

3

Answers


  1. 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

    Login or Signup to reply.
  2. try this code below , it works for me

           public function __construct(
               MagentoCatalogModelProductFactory $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(); 
         }
    
    Login or Signup to reply.
  3. public function __construct(
        MagentoCatalogModelProductFactory $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();
        }
    }
    

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search