How to render Add to cart form programmatically with Drupal Commerce 2
Panier de fraises
Drupal Commerce

I am working on a beautiful Drupal Commerce website this week and I need to render the classical Add to cart form inside a popin - or modal window if you prefer. I've realized I am not the only one who need to do so, therefore I wrote this post to explain how to programmatically render the Cart Form with Drupal Commerce 2. Basically, we will use the great Lazy Builder provided by the Commerce Cart module. Have a look at Drupal\commerce_product\ProductLazyBuilders.php for more details.

The easy way

The easiest way to programmatically render an "Add to cart" form for a product is to return the Lazy Builder in as render array - in a preprocess function for instance.

 * Implements hook_preprocess_block()
function mymodule_preprocess_node(&$variables) { 
  $combine = TRUE;
  $langcode = 'en';
  $view_mode = 'cart';
  $product_id = 123456; // An arbitrary product ID.

  $variables['add_to_cart_form'] = [
    '#lazy_builder' => [
    '#create_placeholder' => TRUE,

You can now display the form in your template with the {{ add_to_cart_form }} variable, as follow:

{% extends 'node.html.twig' %}

{% block after_footer %}
  {{ add_to_cart_form }}
{% endblock %}


The less easy way

Using preprocess functions is not cool. You will always prefer to have a reusable piece of code somewhere to render you Add to cart form.

To do so, we will create an extra field to display the Form. This method has many benefits :

  • You can show or hide the field in the Product's Display mode
  • You have greater control of the caching strategy
  • You can easily extend it to as many Product Types as you want  



Oups... my form is empty!

If you end up with an empty form, don't panic.

This is certainly because your product can not be added to the cart.

Most of the time it's because it doesn't have available variations or some empty stock.

Double check this product's attributes and clear caches :)