0

How to create a script for update product stock. After the product stock update saves the product. Anyone helps me to create this script.

1

Please use this code in your phtml.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productId = 1; // Your Product ID
$_product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
$_product->setStockData(array(
        'qty' => 300 //your Qty
    )
);
$_product->save();

I just tried it works. !!

  • We want this from custom phtml file – Anil Jun 17 at 12:17
  • @Anil I have updated my answer, try this one. – Abdul Pathan Jun 17 at 13:04
0

Below I have write simple code for update product stock.

    <?php

namespace Agtech\Productstockupdate\Block\Index;


class Index extends \Magento\Framework\View\Element\Template {

    protected $productFactory;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->productFactory = $productFactory;
    }

    public function updateStock($productId,$productQty)
    {
        $product = $this->productFactory->create()->load($productId);

        $product->setStockData(
            [
                'use_config_manage_stock' => 0, //'Use config settings' checkbox
                'manage_stock' => 1, //manage product stock
                'is_in_stock' => 1, //Stock Availability
                'qty' => $productQty, //QTY
            ]
        );
        $product->save();
    }

}

open your Phtml file and call this function $block->updateStock($productId,$productQty). like $block->updateStock(10,100) Run Cammand

  • We want this functionality using phtml file. When we run this file in front side then product stock update. – Anil Jun 17 at 12:27
  • @Anil Create block file into you module and add above code after that call updateStock function into phtml file . like $block->updateStock($productId,$productQty). I have edited code – Shorabh Jun 17 at 12:31
  • We don't clear what you say. because of we are not more familiar with coding. – Anil Jun 17 at 12:40
  • please give your phtml file path and module name. Also give block name and path if you have – Shorabh Jun 17 at 12:46
  • Module Name => Agtech/Productstockupdate Phtml file path => app/code/Agtech/Productstockupdate/view/frontend/templates/productstockupdate_index_index.phtml – Anil Jun 17 at 12:50

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.