admin管理员组文章数量:1431927
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.
本文标签: phpHow to create a proudct and variant in Craft commerce 5Stack Overflow
版权声明:本文标题:php - How to create a proudct and variant in Craft commerce 5? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745587862a2665017.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论