Hi!
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.
Comments
Comment #2
jpdaut CreditAttribution: jpdaut commentedI completely second this, I need it too.
Comment #3
mbreden CreditAttribution: mbreden at Acro Commerce commentedI will try to explain how to programmatically add stores, products, etc.
Creating a store
It all starts at the store. Products, orders, etc all reference a store. For most sites, there will probably only be a single store. Orders belong to a single store, whereas products can belong to many stores.
Loading a store
If you already have a store, you can load by it's id:
Creating a product variation
Now that we have a store, we can create products and their variations. Every product needs a variation first.
Creating a custom product variation type and attributes
If you want to make custom attributes for your products, you will most likely want to use a custom variation type and add the custom attributes & values to it.
Creating a product
Next up, we need to make the product itself.
Creating custom product types
To make a custom product type that references a specific variation type, you do this.
Creating orders
Now that we have a store, product variations and products, we can add orders and order items.
If I missed anything I will update this post. Hope it helps!
Comment #4
jpdaut CreditAttribution: jpdaut commentedThis is great thank you so much! I went as far as the products, everything works, I have a couple questions.
1/ The variation title is not carried through into the product, it says N/A on the product edit form. Why is that? In the docs it says "Variations do not have labels or titles". But when you add a variation from a product variation type, the title is set to the attribute value chosen. So, this is confusing to me at the moment. Can you clarify?
2/ Your example demonstrates a variation which is a regular fieldset on the product. But my product type uses a variation type, which has an attribute with several possible values on it. I'd like to create the product with all the variations. Could you explain how to programmatically retrieve the variation type, then each of its attribute value, to create the variations with their Price and SKU? This would be most helpful. Thank you.
Comment #5
mbreden CreditAttribution: mbreden at Acro Commerce commentedI updated my post above to include "Creating a custom product variation type and attributes".
For 1)
If you take a look at my updated part, you'll see 'generateTitle' => TRUE, under the variation type. If this is set to true (as is on the default variation type) then the code will automatically generate titles for each variation, basing it on the product name itself and the attribute names. (IE "Shirt - Blue, Large").
If generateTitle is set to false, then the title given to it will stay.
For 2)
I hope I mostly answered this question with the updated code. If you want to retrieve a list of values for a product variation, you can call
$variation->getAttributeValues()
That helpful?
Comment #6
mbreden CreditAttribution: mbreden at Acro Commerce commentedI've create an issue to follow up and add these to the official docs so it's always available, with more examples and information.
https://www.drupal.org/node/2817491
If you have any more questions you can keep asking them here and I'll try and stay on top of it.
Comment #7
jpdaut CreditAttribution: jpdaut commentedYes this really helps. I'm only missing one step : that of creating the product type that has the variation type with color, so that the product created can be of that type. Could you please add that? It would be absolutely great. Thanks.
Comment #8
mbreden CreditAttribution: mbreden at Acro Commerce commentedAhh, I missed that. OK I added it up there underneath custom products. Was there anything else, or does that mostly cover it now?
Comment #9
jpdaut CreditAttribution: jpdaut commentedWorks perfectly. One more thing would be to show how to create the product with not just the red attribute variation like now, but also with the blue attribute variation (not created in the example currently). So, create the product with both variations in one call, how would the code look to do that? This would be very useful.
Finally, for this great tutorial and the API docs, could you show boilerplate code to load things, like load all variation types, all product types. Also, how to load all products of a specific product type. And finally finally how to add a variation to a product. I hope this is not too much asking! Thanks!
Comment #10
sun-fire CreditAttribution: sun-fire commentedThank you so much! This really helps in development!
Comment #11
mbreden CreditAttribution: mbreden at Acro Commerce commentedThe official docs now have a 'recipe' section, check it out: http://docs.drupalcommerce.org/v2/recipes/
If you copy/paste the code from top to bottom, it will all work. It also shows how to load entities, and how to add multiple attributes to a variation type, and multiple variations to the same product.
Also, if you want to know how to load an entity by it's property (like it's type), you can use this:
Comment #12
bojanz CreditAttribution: bojanz at Centarro commentedWe now have docs, the repository is at https://github.com/drupalcommerce/commerce-docs for you to send pull requests or open issues against. Thanks, everyone.
Comment #14
suresh.senthatti CreditAttribution: suresh.senthatti commentedCould anyone knows, how to do the product insert with multi language?
Comment #15
Parthvi CreditAttribution: Parthvi commentedYes, how to do the product insert with multi language? and How to edit existing product?
Anybody please help!
Comment #16
Parthvi CreditAttribution: Parthvi commentedI am looking for the product delete code also.
I tried \Drupal\commerce_product\Entity\Product::delete($product_id); but not working.
Is there any way to delete multiple products?
Thanks in advance.
Comment #17
sun-fire CreditAttribution: sun-fire commentedHi!
About #15 - it's a fairly simple (how to edit existing products):
With this code you can load the product, next you can apply your changes, and next just:
Comment #18
sun-fire CreditAttribution: sun-fire commentedAbout #16 - I think you can try something like this:
I didn't tested that code, but I think, it's should working, because entity_delete_multiple is a standard function for working with entities.
Comment #19
bharat.kelotra CreditAttribution: bharat.kelotra commentedHow can we load a product/variation by sku (not product id) and do update of price/status programmatically?
Comment #20
mglamanThere's a lot of support comments here, which are off topic.
Your going to get better results by posting questions at https://drupal.stackexchange.com/. Most of these are generic Drupal questions and not specific to just Commerce.
Comment #21
mglamanComment #22
Parthvi CreditAttribution: Parthvi commentedHi,
Thanks for the reply.
I can add translation for category via below code.
$term1NL = $term1->addTranslation('nl');
$term1NL->name = 'nl version';
$term1NL->vid = 'main cat';
$term1NL->save();
How can I edit translation?
Comment #23
.jch CreditAttribution: .jch as a volunteer and commentedUpdating all variations => When editing a product and saving, it's variations are not updated. If fields in the variations are comprised of fields from the parent product type such as a SKU partially made from tokens derived from drop-down lists in product type, then these fields are not updated in the product variations unless manually going into each variation and doing a Edit / Update on every variation to synchronize fields.
What would the code look like in order to include an option to Update ALL variations on the product edit form, Or simply adding
a variation update loop to Product Edit Save?
What's needed is possibly some kind of bulk update to synchronize products variations with their product type and probably orders as well.
Comment #24
wanjee CreditAttribution: wanjee commentedRecipe to programmatically create a product (and its variation) fails in my case:
I get following error:
Error: Call to a member function isEmpty() on null in Drupal\commerce_product\Entity\Product->postSave() (line 285 of [...]/modules/contrib/commerce/modules/product/src/Entity/Product.php) #0 [...]/core/lib/Drupal/Core/Entity/EntityStorageBase.php(469): Drupal\commerce_product\Entity\Product->postSave(Object(Drupal\commerce\CommerceContentEntityStorage), false)
Are #3 documentation still up-to-date ? I use 8.x-2.3.
Thanks
Comment #25
drugan CreditAttribution: drugan as a volunteer commentedAs an alternative you may try for this purpose the Commerce Bulk module:
https://www.drupal.org/project/commerce_bulk
See how the Commerce Generate submodule generates products using Variations Creator service:
https://github.com/drugan/commerce_bulk/blob/8.x-1.x/modules/commerce_ge...
Also, see how variations are bulk created for a product:
https://github.com/drugan/commerce_bulk/blob/8.x-1.x/commerce_bulk.modul...
Explore the service class methods:
https://github.com/drugan/commerce_bulk/blob/8.x-1.x/src/BulkVariationsC...
Comment #26
wanjee CreditAttribution: wanjee commentedHi drugan, thanks for the insights.
I was able to make some progress looking at your code. Main change is the removal of $variation->save(); as it does not seem necessary.
This is the working code.
Thanks !
Comment #27
swatiphp CreditAttribution: swatiphp as a volunteer commented@mbreden Thanks for code example.
I would like to know how can I set value for custom fields created on "default" type from manage fields.
Comment #28
taggartj CreditAttribution: taggartj as a volunteer commentedBookmarked ! :)
Comment #29
taggartj CreditAttribution: taggartj as a volunteer commentedAlso can look in to using the Services ... in my case was simply trying to programmatically add stuff to a the cart:
Comment #30
handkerchiefAttention: You can't remove the variation->save() method as it says in #26 if you are in a product presave hook. For that you have to save the variation first, otherwise you'll get this error:
Drupal\Core\Entity\EntityStorageException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'variations_target_id' cannot be null
Comment #31
liquidcms CreditAttribution: liquidcms commentedWas trying to write a function to create a cart with line items from a product id. Using excellent write up from #3 above (with a couple minor tweaks) i was able to get the Order created; but no cart.
Doesn't look like the Commerce docs referenced above have anything on Cart programming; but on a whim.. i tried setting $order->cart = true.. and sure enough.. i got a cart created. :)
Comment #32
liquidcms CreditAttribution: liquidcms commentedHmm.. no, not quite.. still issues with this.
If i add again, then /cart has multiple carts with multiple checkout buttons. Even after i delete the orders. Seems like still a few bugs in this.
Comment #33
ZRoman CreditAttribution: ZRoman commentedi create product this code
, but look error
Fatal error: Class 'Drupal\Tests\commerce\Kernel\CommerceKernelTestBase' not found...