मैं साधारण उत्पाद को जादुई तरीके से बनाना चाहता हूँ 2. क्या कोई बनाने का कोई तरीका है?
मैं साधारण उत्पाद को जादुई तरीके से बनाना चाहता हूँ 2. क्या कोई बनाने का कोई तरीका है?
जवाबों:
यहां, मुझे कस्टम 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();
?>
सबसे पहले, अपने निर्माता में आप निर्भरता इंजेक्शन के लिए तीन वर्गों में शामिल करना चाहते हैं: Magento\Catalog\Api\Data\ProductInterfaceFactory
, Magento\Catalog\Api\ProductRepositoryInterface
और Magento\CatalogInventory\Api\StockRegistryInterface
। पहला जनरेट किया गया है, इसलिए बहुत चिंतित न हों अगर यह दिखाता है कि आपके आईडीई में मौजूद नहीं है।
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;
}
वहां से, जहां आप उत्पाद बनाना चाहते हैं, आपको इसे बनाने और डेटा सेट करने के लिए फ़ैक्टरी का उपयोग करना होगा, और इसे बचाने के लिए भंडार:
/** @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 */
}
);
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/
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()