27

I'd like to create simple product programmatically in magento 2. Is there any way to create ?

5 Answers 5

39

First, in your constructor you'll want to include three classes for dependency injection: Magento\Catalog\Api\Data\ProductInterfaceFactory, Magento\Catalog\Api\ProductRepositoryInterface and Magento\CatalogInventory\Api\StockRegistryInterface. The first is generated, so don't get too concerned if it shows up as not existing in your IDE.

public function __construct(\Magento\Catalog\Api\Data\ProductInterfaceFactory $productFactory, \Magento\Catalog\Api\ProductRepositoryInterface $productRepository, \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry)
{
    $this->productFactory = $productFactory;
    $this->productRepository = $productRepository;
    $this->stockRegistry = $stockRegistry;
}

From there, where you want to create the product, you'll need to use the Factory to create it and set the data, and the repository to save it:

/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $this->productFactory->create();
$product->setSku('SAMPLE-ITEM');
$product->setName('Sample Item');
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE);
$product->setVisibility(4);
$product->setPrice(1);
$product->setAttributeSetId(4); // Default attribute set for products
$product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
// If desired, you can set a tax class like so:
$product->setCustomAttribute('tax_class_id', $taxClassId);

$product = $this->productRepository->save($product); // This is important - the version provided and the version returned will be different objects

You'll likely then want to add some stock for it, which you can do like this:

$stockItem = $this->stockRegistry->getStockItemBySku($product->getSku());
$stockItem->setIsInStock($isInStock);
$stockItem->setQty($stockQty);
$this->stockRegistry->updateStockItemBySku($product->getSku(), $stockItem);

If you're running this in a script (including setup/upgrade scripts), then you're also going to need to emulate the area as this sort of thing requires sessions for some crazy reason.

To do that, pull in \Magento\Framework\App\State through the constructor, and then utilize this code:

$this->state->emulateAreaCode(
    'adminhtml', 
    function () { 
        /* all code here */ 
    }
);
1
  • just a little addition, instead of adding all the code inside the callback function, one can also do it this way, $this->appState->emulateAreaCode( 'adminhtml', [$this, "saveProduct"], [$_product] ); where saveProduct is a class method public function saveProduct(ProductInterface $_product){$_savedProduct = $this->productRepository->save($_product);}
    – Haijerome
    Commented Dec 18, 2020 at 12:55
28

Here, I found the solutions to create a product programmatically via custom php file i.e. test.php .

<?php
use Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');


$_product = $objectManager->create('Magento\Catalog\Model\Product');
$_product->setName('Test Product');
$_product->setTypeId('simple');
$_product->setAttributeSetId(4);
$_product->setSku('test-SKU');
$_product->setWebsiteIds(array(1));
$_product->setVisibility(4);
$_product->setPrice(array(1));
$_product->setImage('/testimg/test.jpg');
$_product->setSmallImage('/testimg/test.jpg');
$_product->setThumbnail('/testimg/test.jpg');
$_product->setStockData(array(
        'use_config_manage_stock' => 0, //'Use config settings' checkbox
        'manage_stock' => 1, //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' => 100 //qty
        )
    );

$_product->save();
?>
7
  • 16
    Please don't use (or advocate use of) standalone scripts and the object manager to get things done. It's very poor form.
    – Ryan Hoerr
    Commented Feb 23, 2016 at 13:36
  • @RyanHoerr I realise your comment is several months old, but what would you suggest instead?
    – Someone
    Commented Oct 14, 2016 at 10:41
  • 2
    My recommendation would be a custom module and CLI command. I lay that out with documentation links here: magento.stackexchange.com/a/102901/1905 -- That is to say, rather than a standalone script, use a module; rather than $objectManager, use Dependency Injection to get the necessary objects.
    – Ryan Hoerr
    Commented Oct 14, 2016 at 13:03
  • 1
    @RyanHoerr Thanks for the link, however I'm not sure how to use that in the context of creating a product. Also thanks Ankit, but your link is very similar to what is already here (i.e, using the objectManager).
    – Someone
    Commented Oct 26, 2016 at 13:25
  • 4
    @RyanHoerr sorry for replying to such an old thread. Modules and CLI commands are not always an option. If I want to access Magento from within my own software (living on the same server) and usage of API is too slow, the only option I see is using the objectmanager.
    – mniess
    Commented Jan 5, 2018 at 12:58
8
use \Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');

// add bootstrap
$bootstraps = Bootstrap::create(BP, $_SERVER);
$object_Manager = $bootstraps->getObjectManager();

$app_state = $object_Manager->get('\Magento\Framework\App\State');
$app_state->setAreaCode('frontend');

// get date 
$today_date = date("m/d/Y");
$added_date = date('m/d/Y',strtotime("+17 day"));

$set_product = $object_Manager->create('\Magento\Catalog\Model\Product');

try{
    $set_product->setWebsiteIds(array(1));
    $set_product->setAttributeSetId(4);
    $set_product->setTypeId('simple');
    $set_product->setCreatedAt(strtotime('now')); 
    // time of product creation
    $set_product->setName('Test Sample Products'); 
    // add Name of Product
    $set_product->setSku('add-sku-1');
    // add sku hear
    $set_product->setWeight(1.0000);
    // add weight of product
    $set_product->setStatus(1);
    $category_id= array(4,5);
    // add your catagory id
    $set_product->setCategoryIds($category_id); 
    // Product Category
    $set_product->setTaxClassId(0); 
    // type of tax class 
    // (0 - none, 1 - default, 2 - taxable, 4 - shipping)
    $set_product->setVisibility(4); 
    // catalog and search visibility
    $set_product->setManufacturer(28); 
    // manufacturer id
    $set_product->setColor(24);
    //print_r($_product);die;
    $set_product->setNewsFromDate($today_date); 
    // product set as new from
    $set_product->setNewsToDate($added_date); 
    // add image path hear
    $set_product->setImage('/testimg/test.jpg');
    // add small image path hear
    $set_product->setSmallImage('/testimg/test.jpg');
    // add Thumbnail image path hear
    $set_product->setThumbnail('/testimg/test.jpg');
    // product set as new to
    $set_product->setCountryOfManufacture('AF'); 
    // country of manufacture (2-letter country code)
    $set_product->setPrice(100.99) ;
    // price in form 100.99
    $set_product->setCost(88.33); 
    // price in form 88.33
    $set_product->setSpecialPrice(99.85); 
    // special price in form 99.85
    $set_product->setSpecialFromDate('06/1/2016'); 
    // special price from (MM-DD-YYYY)
    $set_product->setSpecialToDate('06/30/2018'); 
    // special price to (MM-DD-YYYY)
    $set_product->setMsrpEnabled(1); 
    // enable MAP
    $set_product->setMsrpDisplayActualPriceType(1); 
    // display actual price 
    // (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
    $set_product->setMsrp(99.99); 
    // Manufacturer's Suggested Retail Price
    $set_product->setMetaTitle('test meta title 2');
    $set_product->setMetaKeyword('test meta keyword 2');
    $set_product->setMetaDescription('test meta description 2');
    $set_product->setDescription('This is a long description');
    $set_product->setShortDescription('This is a short description');
    $set_product->setStockData(
        array(
        'use_config_manage_stock' => 0, 
        // checkbox for 'Use config settings' 
        'manage_stock' => 1, // manage stock
        'min_sale_qty' => 1, // Shopping Cart Minimum Qty Allowed 
        'max_sale_qty' => 2, // Shopping Cart Maximum Qty Allowed
        'is_in_stock' => 1, // Stock Availability of product
        'qty' => 100 // qty of product
        )
    );

    $set_product->save();
    // get id of product
    $get_product_id = $set_product->getId();
    echo "Upload simple product id :: ".$get_product_id."\n";
}
catch(Exception $exception)
{
    // errro in exception/code
    Mage::log($exception->getMessage());
}

code reference :: https://www.onlinecode.org/create-a-simple-product-programmatically-in-magento-2/

8
1

in addition to these answers, to assign product to one or more categories, it might help someone.

use Magento\Catalog\Api\CategoryLinkManagementInterface;

/**
 * @var CategoryLinkManagementInterface
 */
private $categoryLinkManagementInterface;

public function __construct(
    CategoryLinkManagementInterface $categoryLinkManagementInterface
) {
    $this->categoryLinkManagementInterface = $categoryLinkManagementInterface;
}

$category_ids = [457, 236, 145];
$this->categoryLinkManagementInterface->assignProductToCategories($sku, $category_ids);
0
use Magento\Framework\App\Filesystem\DirectoryList; 
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
class Addsimpleproduct extends \Magento\Framework\App\Action\Action
{
protected $_resultPageFactory;
protected $_fileUploaderFactory;
public function __construct(Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory)
{
    //  $t$this->_fileUploaderFactory = $fileUploaderFactory;
    // $this->filesystem = $filesystem;
    $this->_resultPageFactory = $resultPageFactory;
    parent::__construct($context);
}


public function execute()
{
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $islogin = $objectManager->create('Magento\Customer\Model\Session');    // check is login
    if(!$islogin->isLoggedIn()) 
    {
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        $url='customer/account/login';
        $resultRedirect->setPath($url);
        $this->messageManager->addSuccess(__('Session Expired...!')); 
        return $resultRedirect;
        exit;
    }

    $_id=$this->getRequest()->getParam('_id');

    $category =     $this->getRequest()->getParam('categorylist');
    $pname      = $this->getRequest()->getParam('pname');
    $pdescription      = $this->getRequest()->getParam('pdescription');
    $pshortdescription      = $this->getRequest()->getParam('pshortdescription');
    $sku      = $this->getRequest()->getParam('sku');
    $price      = $this->getRequest()->getParam('price');
    $spprice      = $this->getRequest()->getParam('spprice');
    $spfrom      = $this->getRequest()->getParam('spfrom');
    $spto      = $this->getRequest()->getParam('spto');
    $stock      = $this->getRequest()->getParam('stock');
    $stockavailiable      = $this->getRequest()->getParam('stockavailiable');
    $visiblibilty      = $this->getRequest()->getParam('visiblibilty');
    $tax      = $this->getRequest()->getParam('taxclass');
    $weight_radio= $this->getRequest()->getParam('weight_radio');

    if($weight_radio==1)
    {
        $weight   = $this->getRequest()->getParam('weight');
    }

    $metatitle      = $this->getRequest()->getParam('metatitle');
    $metakey      = $this->getRequest()->getParam('metakey');
    $metadesc      = $this->getRequest()->getParam('metadesc');
    $maxqty      = $this->getRequest()->getParam('maxqty');
    $download    = $this->getRequest()->getParam('download');
    $virtual=$this->getRequest()->getParam('producttype');
    $title1 = "";
    $title2 = "";
    $separately1 = 0;
            $is_down = "simple";   
    $data =  $objectManager->get('\Magento\Catalog\Model\Product');
    if($_id!="")
    {
        $data ->load($_id);
    }
    $data
        ->setWebsiteIds(array(1))
        ->setStoreId(1) //you can set data in store scope               
        ->setAttributeSetId(4) //ID of a attribute set named 'default'
        ->setTypeId($is_down) //product type
        ->setCreatedAt(strtotime('now')) //product creation time
        ->setSku($sku); //SKU
        if($weight_radio==1)
        {
            $data->setWeight($weight);        
        }
        $data->setName($pname) //product name
        ->setStatus(2) //product status (1 - enabled, 2 - disabled)
        ->setTaxClassId($tax) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)              
        ->setVisibility($visiblibilty)
        ->setPrice($price) //price in form 11.22
        ->setSpecialPrice($spprice) //special price in form 11.22
        ->setSpecialFromDate($spfrom) //special price from (MM-DD-YYYY)
        ->setSpecialToDate($spto) //special price to (MM-DD-YYYY)
        ->setMetaTitle($metatitle)
        ->setMetaKeyword($metakey)
        ->setMetaDescription($metadesc)
        ->setDescription( $pdescription)
        ->setShortDescription($pshortdescription)
        ->setCategoryIds($category)
        ->setStockData(array(
                        'manage_stock' => 1,
                        'max_sale_qty' => $maxqty, //Maximum Qty Allowed in Shopping Cart
                        'is_in_stock' => $stockavailiable,
                        'qty' => $stock
                    )
                );

        // $data->setQuantityAndStockStatus(['qty' => $stock, 'is_in_stock' => $stockavailiable]);

        if($download=='yes')
        {
            $data->setData('links_title',$title1);
            $data->setData('samples_title',$title2);
            $data->setData('links_purchased_separately',$separately1);
        }


        $customerSession = $objectManager->create('Magento\Customer\Model\Session');
        $sid=$customerSession->getCustomer()->getId();

        $cname=$customerSession->getCustomer()->getName();

        $data->setSellerid($sid);
        $data->setApprovalstatus("Pending");

        //for image upload
         // $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $fileSystem = $objectManager->create('\Magento\Framework\Filesystem');
       //$mediaPath=$fileSystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('tmp/catalog/product');
       $filename= $this->getRequest()->getParam('path');
       $files=explode(',',$filename);

       if($filename!='')
       {

           foreach($files as $file)
           {

                $filepath='/catalog/product' .trim($file);
                try{

                     $data->addImageToMediaGallery($filepath, array('image','thumbnail','small','swatch'), false, false);
                }catch(Exception $e)
                {

                }

           }
       }

            $data->save() //$data->save()
1
  • It shows error The image does not exist.
    – Anees
    Commented Feb 19, 2019 at 6:52

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.