1

Is it possible to render the add to cart form programatically? Something like:

\Drupal::formBuilder()->getForm('Drupal\commerce_cart\Form\AddToCartForm', $product)
1

Yes, possible and very easy.

Short version

You can use this render array.

This will render the Cart form if your product can be added to cart - if it has available variations bascially.

$combine = TRUE;
$langcode = 'en';
$view_mode = 'cart';

$build['add_to_cart_form'] = [
  '#lazy_builder' => [
    'commerce_product.lazy_builders:addToCartForm', [
      $product_id,
      $view_mode,
      $combine,
      $langcode
    ],
  ],
  '#create_placeholder' => TRUE,
];

Full example with a Controller

You can use a custom Controller to render your own Add To Cart form.

First, prepare the route in mymodule.routing.yml:

# Custom route to render Add to cart form.
mymodule.add_to_cart:
  path: '/mymodule/add_to_cart/{product_id}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\CartController::addToCart'
    _title: 'Add to cart'
  requirements:
    _access: 'TRUE'
    product_id: \d+   

Second, create your Controller:

<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for cart routes.
 */
class CartController extends ControllerBase {

  function addToCart(int $product_id) {
    $build = [];

    if (!$product_id) {
      $build['error'] = [
        '#type' => 'item',
        '#markup' => $this->t('Wrong product ID'),
      ];
      return $build;
    }

    $build['add_to_cart_form'] = [
      '#lazy_builder' => [
        'commerce_product.lazy_builders:addToCartForm', [
          $product_id,
          'cart',
          TRUE,
          'fr'
        ],
      ],
      '#create_placeholder' => TRUE,
    ];

    return $build;
  }

}

Finally, add a link to open a modal on front end, as follow:

<a href="/mymodule/add_to_cart/1234" title="Add to cart" class="use-ajax" data-dialog-type="modal" data-dialog-options="{&quot;width&quot;:700}">Add product to cart</a>

Clear cache

You should be good to go! :)

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.