Drupal Commerce Cart
Blog

How to add a Product Programmatically to Drupal Commerce Cart

In last two blog post we discussed the basics of getting started with Drupal Commerce and the steps of e-commerce products creation. As we move forward with our learnings, we will write about how we dealt with those. 

There is Business logic which demands few things out of the box where we create custom modules to aid a process. I came across a situation where we had to use Drupal Commerce module but the product was coming from the content type. Even though we had to import the product as commerce product still we couldn’t use them directly. Here we had to add the product to the cart programmatically where I could only get product id from the URL and that particular product needs to be added to the cart and commerce flow needs to be implemented. 

Showing below are the steps that I have followed to add the product to Drupal Commerce Cart Programmatically. I have Created a Custom Modules ‘my_cart’ to demonstrate the above. 

For the below code to work, we have a dependency of using Drupal commerce modules and its dependent modules.

 

Product to Cart

 

 There you have it, it is nice and simple way to add the product to the Drupal commerce cart.

name: my_cart
type: module
description: Adding Product To Cart Programmatically.
package: Custom
core: 8.x
my_cart.list:
path: '/add/product/{productId}'
defaults:
_controller: '\Drupal\my_cart\Controller\CartsController::addToCart'
_title: ''
requirements:
_permission: 'access content'
productId: \d+
<?php
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\commerce\commerce_product;
use Drupal\commerce;
use Drupal\commerce_cart;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\commerce_cart\CartProviderInterface;
use Drupal\commerce_cart\CartManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Controller routines for products routes.
*/
class CartsController extends ControllerBase {
/**
* The cart manager.
*
* @var \Drupal\commerce_cart\CartManagerInterface
*/
protected $cartManager;
/**
* The cart provider.
*
* @var \Drupal\commerce_cart\CartProviderInterface
*/
protected $cartProvider;
/**
* Constructs a new CartController object.
*
* @param \Drupal\commerce_cart\CartProviderInterface $cart_provider
* The cart provider.
*/
public function __construct(CartManagerInterface $cart_manager,CartProviderInterface $cart_provider) {
$this->cartManager = $cart_manager;
$this->cartProvider = $cart_provider;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('commerce_cart.cart_manager'),
$container->get('commerce_cart.cart_provider')
);
}
public function addToCart($productId) {
$destination = \Drupal::service('path.current')->getPath();
$productObj = Product::load($productId);
$product_variation_id = $productObj->get('variations')
->getValue()[0]['target_id'];
$storeId = $productObj->get('stores')->getValue()[0]['target_id'];
$variationobj = \Drupal::entityTypeManager()
->getStorage('commerce_product_variation')
->load($product_variation_id);
$store = \Drupal::entityTypeManager()
->getStorage('commerce_store')
->load($storeId);
$cart = $this->cartProvider->getCart('default', $store);
if (!$cart) {
$cart = $this->cartProvider->createCart('default', $store);
}
$line_item_type_storage = \Drupal::entityTypeManager()
->getStorage('commerce_order_item_type');
// Process to place order programatically.
$cart_manager = \Drupal::service('commerce_cart.cart_manager');
$line_item = $cart_manager->addEntity($cart, $variationobj);
$response = new RedirectResponse(Url::fromRoute('commerce_cart.page')->toString());
return $response;
}
}

get in touch