在magento 2中以编程方式创建一个简单产品


Answers:


29

在这里,我找到了通过自定义php文件(即)以编程方式创建产品的解决方案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();
?>

11
请不要使用(或主张使用)独立脚本和对象管理器来完成任务。这是非常糟糕的形式。
Ryan Hoerr

@RyanHoerr我知道您的评论已有几个月的历史了,但是您有什么建议呢?
刘易斯

2
我的建议是使用自定义模块和CLI命令。我在这里通过文档链接进行了布局:magento.stackexchange.com/a/102901/1905-也就是说,使用模块而不是独立的脚本;而不是$ objectManager,而是使用依赖注入来获取必要的对象。
瑞安·霍尔

1
@RyanHoerr感谢您的链接,但是我不确定如何在创建产品时使用它。也要感谢Ankit,但是您的链接与此处的链接非常相​​似(即使用objectManager)。
刘易斯

3
@RyanHoerr很抱歉回复这样的旧主题。模块和CLI命令并非始终是一个选项。如果我想从自己的软件(位于同一服务器上)访问Magento,并且API的使用速度太慢,那么我看到的唯一选择就是使用objectmanager。
mniess

23

首先,在你的构造你要包括依赖注入三类:Magento\Catalog\Api\Data\ProductInterfaceFactoryMagento\Catalog\Api\ProductRepositoryInterfaceMagento\CatalogInventory\Api\StockRegistryInterface。第一个生成,因此如果它在您的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;
}

从那里,您要在其中创建产品的地方,需要使用Factory来创建它并设置数据,并使用存储库来保存它:

/** @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

然后,您可能需要为其添加一些库存,您可以这样进行:

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

如果您是在脚本(包括设置/升级脚本)中运行该脚本,那么您还将需要模拟该区域,因为出于某种疯狂的原因,这种事情需要会话。

为此,请\Magento\Framework\App\State遍历构造函数,然后使用以下代码:

$this->state->emulateAreaCode(
    'adminhtml', 
    function () { 
        /* all code here */ 
    }
);

6
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());
}

代码参考:: http://www.onlinecode.org/create-a-simple-product-programmatically-in-magento-2/


setCategoryIds不能与多个类别ID一起使用,只能保存一个类别。
Magento2 Devloper

@ Magento2 Devloper:我也有这个博客::粘性参考onlinecode.org/...
Dhaval戴夫

好的,我已经解决了。
Magento2 Devloper

@ Magento2 Devloper:您能告诉我问题是什么,以便对我有所帮助。
Dhaval Dave


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()

显示错误图像不存在。
Anees
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.