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.