How to create a commerce product in Drupal 9

Create a commerce product in Drupal 9,

Include the Commerce Product, Product Variation and Price class

use Drupal\commerce_product\Entity\ProductVariation;

use Drupal\commerce_product\Entity\Product;

use Drupal\commerce_price\Price;

To create a commerce product, first create the variation associated with the product

$variation = ProductVariation::create([

 'type' => 'default', // product type(default or your custom product type machine name)

 'sku' => 'ES76AB', // unique SKU

 'price' => new Price('24.00', 'AED'), // Price is optional

]);

$variation->save();

$product = Product::create([

 'type' => 'default',

 'title' => t('Desired Product Name'),

 'variations' => $variation,

]);

$product->save();

To create a commerce product, with multiple variations associated with the same product,

$variation_ab = ProductVariation::create([

 'type' => 'default', // product type(default or your custom product type machine name)

 'sku' => 'ES76AB', // unique SKU

 'price' => new Price('24.00', 'AED'), // Price is optional

]);

$variation_ab->save();

$variation_dd = ProductVariation::create([

 'type' => 'default', // product type(default or your custom product type machine name)

 'sku' => 'ES77DD', // unique SKU

 'price' => new Price('24.00', 'AED'), // Price is optional

]);

$variation_dd->save();

$product = Product::create([

 'type' => 'default',

 'title' => t('Desired Product Name'),

 'variations' => [$variation_ab, $variation_dd]

]);

$product->save();

Category