To create a product programmatically using the ProductRepository in Magento 2, you can use the following code:
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\App\State;
use Magento\Framework\Exception\CouldNotSaveException;
$json = '{
"sku": "samsung-a50",
"name": "Samsung A50",
"attribute_set_id": 4,
"price": 150000,
"status": 1,
"visibility": 1,
"type_id": "simple",
"weight": "1"
}';
// Instantiate the object manager and required dependencies
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
$dataObjectHelper = $objectManager->get(DataObjectHelper::class);
$appState = $objectManager->get(State::class);
// Set the application area code to avoid Area code not set exception
$appState->setAreaCode('frontend');
// Create a new product object and set the data from the JSON string
$product = $objectManager->create(ProductInterface::class);
$dataObjectHelper->populateWithArray($product, json_decode($json, true), ProductInterface::class);
// Save the product using the repository
try {
$productRepository->save($product);
echo "Product created successfully.";
} catch (CouldNotSaveException $e) {
echo "Error: " . $e->getMessage();
}
In this code, we first instantiate the ProductRepositoryInterface, DataObjectHelper, and State objects using the object manager. We also set the application area code to avoid the "Area code not set" exception.
Next, we create a new ProductInterface object and use the DataObjectHelper to populate it with the data from the JSON string. We then save the product using the ProductRepositoryInterface.
Note that in the JSON string, you should use the correct product type ID, such as simple, configurable, or virtual. Also, it is recommended to avoid using the object manager directly and instead use dependency injection for better code maintainability and testability.