I am getting json object of product that needs to created in Craft Comemrce 5 but it is creating a product but failing create variant. I tried with below approaches but no luck
- Save product then try to save variant
- Create product and variant at same time
$product->setVariants([$variant]);
Below is my code -
$product = new Product();
$product->typeId = $data['typeId']; // Product type ID
$product->title = 'Test'; // Product title
$product->enabled = $data['enabled'] ?? true; // Enabled status
$product->productDescription = $data['description'] ?? ''; // Description
$product->postDate = new \DateTime();
if (!\Craft::$app->elements->saveElement($product)) {
return false;
}
// Create a single default variant
$variant = new Variant();
$variant->productId = $product->id;
$variant->sku = "ABCD"; // SKU for the variant
$variant->price = 10.01; // Price
// $variant->stock = 1; // Stock level
$variant->hasUnlimitedStock = false; // Manage stock
$variant->isDefault = true; // Mark as default variant
$variant->availableForPurchase = true;
$variant->promotable = true;
$variant->taxCategoryId = 1;
$variant->shippingCategoryId = 1;
if (!\Craft::$app->elements->saveElement($variant)) {
// dd($product->getErrors());
// \Craft::error('Failed to save product with variants: ' . json_encode($product->getErrors()), __METHOD__);
return false;
}
$product->setVariants([$variant]);
if (!\Craft::$app->elements->saveElement($product)) {
Craft::error('Failed to save product with variants: ' . json_encode($product->getErrors()), __METHOD__);
return false;
}
Also, I want to store stock as well but I am getting error that stock is read only attribute.