I'm working on D8 site with Drupal Commerce.
I have to create a dynamic product variation and add it to cart for the user checkout.
The problem I have, is when you land on the cart page, the line item doesn't have a label (title) it replaced with the price of the item. Please refer to the attached image.
Here's my code:
//create variation
$variation = ProductVariation::create([
'type' => 'fk_payment',
'sku' => 'FK'.$faid,
'status' => TRUE,
'price' => new Price($trans->getTotal(), $trans->getCurrency()),
'title' => "Example item label title",
]);
$variation->save();
//Load the product
$product_id = 4;
$product = Product::load($product_id);
$product->addVariation($variation);
$product->save();
//load store
$storeId = $product->get('stores')->getValue()[0]['target_id'];
$store = \Drupal::entityTypeManager()
->getStorage('commerce_store')
->load($storeId);
//prepare cart
$cart = \Drupal::service('commerce_cart.cart_provider');
$cart = $cart->getCart('default', $store);
if (!$cart) {
$cart = \Drupal::service('commerce_cart.cart_provider');
$cart = $cart->createCart('default', $store);
}
// Process to place order programatically.
$cart_manager = \Drupal::service('commerce_cart.cart_manager');
//empty the cart
if (!empty($cart)) {
$cart_manager->emptyCart($cart);
}
$cart_manager->addEntity($cart, $variation);