How to create product and product variations in Drupal 8 for Drupal Commerce

Posted by admin on Wed, 01/17/2018 - 10:18

Code snippets for creating Drupal 8 products and product variations for Drupal Commerce.

Create a product variation first:

// The price of the variation.
$price = new \Drupal\commerce_price\Price('24.99', 'USD');
 
$variation = \Drupal\commerce_product\Entity\ProductVariation::create([
  'type' => 'default', // The default variation type is 'default'.
  'sku' => 'test-product-01', // The variation sku.
  'status' => 1, // The product status. 0 for disabled, 1 for enabled.
  'price' => $price,
]);
$variation->save();

First load your store. If you haven't that - create it!

$store = \Drupal\commerce_store\Entity\Store::load(1);

Create a product attached to that store with that variation created above:

$product = \Drupal\commerce_product\Entity\Product::create([
  'uid' => 1, // The user id that created the product
  'type' => 'default', // Just like variation, the default product type is 'default'
  'title' => 'My product',
  'stores' => [$store], // The store we loaded above
  'variations' => [$variation], // The variation we created above
]);
$product->save();

You can also add a variation to a product using the addVariation() method.

$product->addVariation($variation);
$product->save();
×

Hey! Don't miss a new cool stuff!

Comments

blackberry-girls (not verified)
Brenna (not verified)

Link exchange is nothing else but it is simply placing the other person's webpage

link on your page at proper place and other person will

also do similar in support of you.

Also visit my homepage ... party dress

Raghav Malik (not verified)

We are here to provide you the best Escort Service in Gurgaon with Indian and Russian Escorts along with housewife

Escorts Services in Gurgaon

Russian Call Girls in Gurgaon

Call Girls in Gurgaon

Escorts service in Gurugram

Independent Escorts Gurgaon

Russian Escorts in Gurgaon

Madelaine (not verified)

Thanks in favor of sharing such a fastidious thought, post is fastidious, thats why i have read it completely

My web site: Romeo

Hyderabad Escorts (not verified)
Rowena (not verified)

Simply wish to say your article is as astonishing. The clarity in your post is

just excellent and i could assume you're an expert on this subject.

Fine with your permission allow me to grab your RSS feed to keep updated

with forthcoming post. Thanks a million and please continue

the enjoyable work.

Here is my web-site ... community leader

aftab ali (not verified)

The people must know about these highlights and wish to settle on all choices. In this way, getting all the important data about your life partner is fundamental for you. parimatch

Add new comment