How to set price field value programmatically in Drupal Commerce

Components

Price in Drupal Commerce 2.x is not a number but a class. This class has a price number and currency code properties, and both are strings. So, to set the product price programmatically you have to first instantiate the Price class:

$price = new \Drupal\commerce_price\Price('9.99', 'EUR');

and then use created Price object to set the product price:

$product_variation = \Drupal\commerce_product\Entity\ProductVariation::load(1);
$product_variation->set('price', $price);
$product_variation->save();

To get the price number and currency code you can use appropriate getters methods:

$price_number = $price->getNumber();
$currency_code = $price->getCurrencyCode();

You can also create a Price object by using the static method:

$price = Price::fromArray(['number' => '9.99', 'currency_code' => 'EUR']);

In summary, in Drupal Commerce 2.x, prices are managed using the Price class, which encapsulates both the price number and currency code, allowing for programmatic manipulation and retrieval of product prices. 

About the Author

Goran Nikolovski is a web and AI developer with over 10 years of expertise in PHP, Drupal, Python, JavaScript, React, and React Native. He founded this website and enjoys sharing his knowledge.