I can add an order item from the cart by doing this :


Is there a similar way to delete a product line from my cart ?


Orders have a removeItem method defined on their interface. You just need to pass the loaded order item to that method, and then delete the orderitem.

 * Removes an order item.
 * @param \Drupal\commerce_order\Entity\OrderItemInterface $order_item
 *   The order item.
 * @return $this
public function removeItem(OrderItemInterface $order_item);

See how the commerce_xquantity module does this: https://github.com/drugan/commerce_xquantity/blob/8.x-1.x/src/Entity/XquantityOrderItem.php#L318


Example function on how to remove all the products of specific product type from cart:

function _remove_all_products_of_types($typesToRemove)
  $orders = \Drupal::service('commerce_cart.cart_provider')->getCarts();
  $items = reset($orders)->getItems();

  foreach ($items as $item){
    $productType = $item->getPurchasedEntity()->get('type')[0]->get('target_id')->getValue();
    if (in_array($productType, $typesToRemove)){
      foreach ($orders as $order){

Function parameter is array of product type machine names (strings).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.