Code recipes

Hiding add to cart form for anonymous users

Use hook_form_alter and '#access' => !is_anonymous under add to cart submit

Creating a custom add to cart form

If the default add to cart form lacks some necessary functionality, you can either use a form alter hook or consider this cleaner approach:

  1. Extend commerce_cart\Form\AddToCartForm.php

    • Override any methods to alter the form functionality.
  2. Implement hook_entity_type_build() to swap out the default form with your custom one.
/**
 * Implements hook_entity_type_build().
 */
function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['commerce_order_item']->setFormClass('add_to_cart', '\Drupal\mymodule\Form\AddToCartForm');
}
  1. If your custom module name does not come after commerce_cart alphabetically, then you will need to manually adjust its weight. To do this, you can use hook_module_implements_alter(). Or you can use the module_set_weight API function (implemented in core\includes\module.inc).

Altering commerce product twig template variables

You can use hook_preprocess_commerce_product as in:

function mymodule_preprocess_commerce_product(&$variables) {
  $product = $variables['elements']['#commerce_product'];
  ...
}

Links and resources

Found errors? Think you can improve this documentation? edit this page