Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create products programmatically in Drupal 8 commerce

I'm using current commerce 2.x.dev for online store development. It's first project with Commerce 2 for me.

When i started to work on products import, i found that Feeds module does not stable, and i decided to write custom solution for data import (Batch/Queue API data import from CSV/XML sources).

So, at this moment i cannot find any information about correct product entities creation via code. I explored Drupal Commerce documentation section: http://docs.drupalcommerce.org/v2/product/products.html but it contains only UI instructions for manual products management.

I think that short instruction for working from code with products / orders entities will be very helpful for developers, especially for developers, who starts working with commerce 2 and have some experience with 7.x commerce.

like image 479
sun-fire Avatar asked Oct 05 '16 13:10

sun-fire


1 Answers

To create a product programmatically with 3 product variations, use the following code in a custom module:

use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_product\Entity\Product;
use Drupal\commerce_price\Price;

function my_module_install() { 

// Create variations

$variation1 = ProductVariation::create([
  'type' => 'default',
  'sku' => 'var1',
  'price' => new Price('24.00', 'EUR'),  
]);
$variation1->save();

$variation2 = ProductVariation::create([
  'type' => 'default',
  'sku' => 'var2',
  'price' => new Price('50.00', 'EUR'),  
]);
$variation2->save();

$variation3 = ProductVariation::create([
  'type' => 'default',
  'sku' => 'var3',
  'price' => new Price('115.00', 'EUR'), 
]);
$variation3->save();    

// Create product using variations previously saved

$product = Product::create([
  'type' => 'default',
  'title' => t('Your Product Name'),
  'variations' => [$variation1, $variation2, $variation3],
]);
$product->save();

}

I hope that it answers your question. Feel free for more details.

Best regards

like image 54
Miguel Martins Avatar answered Oct 05 '22 23:10

Miguel Martins