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

Free viagra (not verified)

Hjtdxj toyeap viagra samples Buy pfizer viagra online

EdwinSeeme (not verified)

installment loans for self employed with bad credit badcreditloans01.com short term loans for bad credit same day.
usa online casino no deposit bonus onlinecasinonodeposit.site free online casino win real money no deposit.

Alternative for... (not verified)

Etushr xkflxp online casinos for usa players golden nugget online casino

EdwinSeeme (not verified)

utah payday loans paydayloans01.com amg services payday loans.
usa casino online real money onlinecasino002 online casino with no deposit.

Generic viagra us (not verified)

Dqeiqw dbggop casino moons online casino casino online slots

EdwinSeeme (not verified)

va loans bad credit consolidation loans for bad credit bad credit personal loans guaranteed approval ny.
online casino free spins no deposit onlinecasinonodeposit.website nj online casino no deposit.

Generic viagra ... (not verified)

Nyktwv iqznpy instant payday loans loans with bad credit

Pharmacy viagra (not verified)

Ckytan xesrvu best payday loans casino real money

Kennethglobe (not verified)

free casino slots online online casino free credit no deposit casino online no deposit.
discover personal loans contact onemain financial personal loans bankofamerica personal loans.

Sale viagra (not verified)

Ibzpco umdcyp generic tadalafil pharmacy online

Buy viagra us (not verified)

Dnlkan spoqms online loan pay day loans

Kennethglobe (not verified)

casino royale watch online free online casino no deposit bonus real vegas online casino no deposit bonus codes.
online casino real money onlinecasinorealmoney.website online casino games for real money for free.

Kennethglobe (not verified)

casino royale watch online free online casino no deposit bonus real vegas online casino no deposit bonus codes.
online casino real money onlinecasinorealmoney.website online casino games for real money for free.

Buy viagra no p... (not verified)

Stilqs gvxloc personal loan bad credit loans with bad credit

Haroldzex (not verified)

online casino games free onlinecasino001.com no deposit online casino.
cash payday loans payday loans direct lender ez payday loans locations.
guaranteed personal loans $5000 best online personal loans banks that do personal loans.
online casino real money usa onlinecasinonodeposit casino play online.

Viagra alternative (not verified)

Czkyqg vtocpw loans for bad credit big fish casino online

Charleskap (not verified)

avant personal loans review small personal loans near me personal loans for low income.
payday loans with ssi debit card paydayloans1.site payday loans colorado springs.
bad credit collateral loans bad credit loans monthly payments direct lenders bad credit installment loans not payday loans.
best debt consolidation loans for bad credit bad credit rv loans bbb accredited personal loans for bad credit.

Williamsmons (not verified)

Fantastic forum posts, Many thanks. canadian viagra

Williamsmons (not verified)

Fantastic forum posts, Many thanks. canadian viagra

WalterShund (not verified)

payday loans deposited on prepaid debit card payday loans georgetown ky get out of payday loans.
loandepot personal loans personalloans1 ally bank personal loans.
no teletrack payday loans direct lenders 100 approval online payday loans direct lenders are payday loans legal in ny.
discover card personal loans bad credit car loans pros and cons of personal loans to pay off credit card debt.

Price viagra (not verified)

Opnwrw egjtwg payday loans for bad credit online casino real money paypal

Price viagra (not verified)

Opnwrw egjtwg payday loans for bad credit online casino real money paypal

Williamsmons (not verified)

Really many of amazing facts! canadian online pharmacy

phefewedy (not verified)

No Rx Online Pharmacy https://agenericcialise.com/ - Cialis Order From Phone Amoxicillin Cialis Propecia En Valencia

phefewedy (not verified)

No Rx Online Pharmacy https://agenericcialise.com/ - Cialis Order From Phone Amoxicillin Cialis Propecia En Valencia

phefewedy (not verified)

No Rx Online Pharmacy https://agenericcialise.com/ - Cialis Order From Phone Amoxicillin Cialis Propecia En Valencia

Williamsmons (not verified)

Seriously tons of awesome info! canadian drug

Williamsmons (not verified)

Seriously tons of awesome info! canadian drug

Cost of viagra (not verified)

Blpmxd nuknxw loans online payday loan online

Cost of viagra (not verified)

Blpmxd nuknxw loans online payday loan online

generic viagra india (not verified)

Jrmzkg xpryvq amoxicillin without a doctor amoxicilina 500 mg

generic viagra india (not verified)

Jrmzkg xpryvq amoxicillin without a doctor amoxicilina 500 mg

Jerryentew (not verified)

Знаете ли вы?
Российских легкоалетов могут сурово наказать за действия чиновников от спорта.
Вместо Плещеева озера Пётр I мог построить потешный флот на озере Неро.
Во время немецкой оккупации Украины радио на украинском языке вещало из Саратова и Москвы.
Кустурица пропустил получение «Золотой ветви» в Каннах, так как любит друзей больше, чем церемонии награждения.
Китайскую пустыню засадили лесами и открыли там фешенебельный курорт.

arbeca

HerbertFiday (not verified)

arizona payday loans quick payday loans utah payday loans.
payday loans no checking account or savings account installment payday loans online bad credit payday loans maine.
payday loans no credit check no employment verification usa payday loans easiest payday loans to get approved for.
loans with bad credit online badcreditloans02 is bad credit loans legit.

HerbertFiday (not verified)

arizona payday loans quick payday loans utah payday loans.
payday loans no checking account or savings account installment payday loans online bad credit payday loans maine.
payday loans no credit check no employment verification usa payday loans easiest payday loans to get approved for.
loans with bad credit online badcreditloans02 is bad credit loans legit.

HerbertFiday (not verified)

arizona payday loans quick payday loans utah payday loans.
payday loans no checking account or savings account installment payday loans online bad credit payday loans maine.
payday loans no credit check no employment verification usa payday loans easiest payday loans to get approved for.
loans with bad credit online badcreditloans02 is bad credit loans legit.

Jerryentew (not verified)

Знаете ли вы?
Залётная птаха занесена в перечень птиц России спустя более полувека после открытия вида.
Не удержавшись от писательства, Амалия Кахана-Кармон создала одну из важнейших книг в истории Израиля.
Андрогинный псевдоним не спас автора от расшифровки.
Американская энциклопедия включила в себя десятки статей о вымышленных людях, якобы связанных с Латинской Америкой.
По выбору Утёсова дорога на Берлин шла то через Минск, то через Киев.

http://www.arbeca.net/

Jerryentew (not verified)

Знаете ли вы?
Залётная птаха занесена в перечень птиц России спустя более полувека после открытия вида.
Не удержавшись от писательства, Амалия Кахана-Кармон создала одну из важнейших книг в истории Израиля.
Андрогинный псевдоним не спас автора от расшифровки.
Американская энциклопедия включила в себя десятки статей о вымышленных людях, якобы связанных с Латинской Америкой.
По выбору Утёсова дорога на Берлин шла то через Минск, то через Киев.

http://www.arbeca.net/

Williamsmons (not verified)

Helpful stuff. Kudos. london drugs canada

Williamsmons (not verified)

Helpful stuff. Kudos. london drugs canada

Jerryentew (not verified)

Знаете ли вы?
Издательство «Шиповник» было задумано для публикации сатиры, однако вместо неё печатало Лагерлёф, Бунина и Джерома Джерома.
Видеоигру с простейшей графикой называли и шедевром, и троллингом.
Новый вид пауков-скакунов был назван по имени писателя в честь юбилея его самой известной книги о гусенице.
Залётная птаха занесена в перечень птиц России спустя более полувека после открытия вида.
В 1941 году в московскую «Писательскую роту» пришли добровольцами бывший вор и следователь ЧК.

http://arbeca.net

Williamsmons (not verified)

You explained it perfectly. london drugs canada

Williamsmons (not verified)

You explained it perfectly. london drugs canada

Williamsmons (not verified)

You explained it perfectly. london drugs canada

Williamsmons (not verified)

You explained it perfectly. london drugs canada

purchasing cial... (not verified)

Hetpja baemze lasix medication furosemide 100 mg

HerbertFiday (not verified)

payday loans in maryland short term payday loans payday loans by phone.
bbb accredited personal loans for bad credit badcreditloans1.site barclay personal loans.
las vegas casino online no deposit bonus codes online casino game casino usa online no deposit.
guaranteed personal loans $5000 interest on personal loans personal loans no credit check online.

cialis generic name (not verified)

Pieign pnxenb buy Tadacip Avana

viagra 100mg (not verified)

Fifueu odibjj buy zithromax buy azithromycin

Add new comment