0

I'm using magento v2.5.5 to develop an extension, in this extension i have to generate virtual product with non manageble stock (infinite stock), how to do this programmatically, my virtual product data example:

$products[] = array(
  'Name' => 'Chocolate',
  'price' => '2000',
  'sku' => 'choco',
  'tax_class_id' => '0',
  'visibility' => '4'
);

$products[] = array(
  'Name' => 'Milk',
  'price' => '1200',
  'sku' => 'milk',
  'tax_class_id' => '0',
  'visibility' => '4'
);

1 Answer 1

1

Use following code to create virtual product. for quantity just use 'manage_stock' => 0,

protected $_product;  


  public function __construct(

        \Magento\Catalog\Model\ProductFactory $_productloader

    ) {


        $this->_productloader = $_productloader;

    }
    public function createProduct()
    {

        $_product = $this->_productloader->create();
        $_product->setName('First Test Product');
        $_product->setTypeId('virtual');
        $_product->setAttributeSetId(4);
        $_product->setSku('test-SKU');
        $_product->setWebsiteIds(array(1));
        $_product->setVisibility(4);
        $_product->setPrice(400);
        $_product->setStockData(array(
            'use_config_manage_stock' => 0, //'Use config settings' checkbox
            'manage_stock' => 0, //manage stock
            'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
            'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
            'is_in_stock' => 1, //Stock Availability
            'qty' => 1000 //qty
            )
        );

        $_product->save();
        echo $_product->getId();
    }
2
  • why setPrice paramater is an array ? Commented Aug 2, 2018 at 8:01
  • @TinyDancer sorry code was not tested i tested now it is working fine. Commented Aug 2, 2018 at 8:08

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.