Simple function for creating an add-to-cart box

Created on 20 January 2012, over 13 years ago
Updated 4 July 2025, 2 days ago

It would really help if there was a simple function for creating an add-to-cart box, for occasions when other APIs are lacking. After perusing example code elsewhere, this is what I came up with:

/**
 * Create a simple add-to-cart form.
 *
 * @param $product_id
 *   The ID of the product to display.
 * @param $quantity
 *   The default number to be added to the cart, defaults to 1.
 * @param $show_quantity
 *   Boolean indicating whether or not to provide the quantity selector.
 * @param $order_id
 *   The order ID to be used, defaults to 0.
 *
 * @return
 *   A formatted add-to-cart form.
 */
function commerce_cart_simple_add_to_cart_form($product_id, $quantity = 1, $show_quantity = FALSE, $order_id = 0) {
  // Load the product.
  $product = commerce_product_load($product_id);

  // Build the line item object.
  $line_item = commerce_line_item_new($product->type, $order_id);
  $line_item->data['context']['product_ids'] = array($product->product_id);
  $line_item->quantity = $quantity;

  // Get the form_id.
  $form_id = commerce_cart_add_to_cart_form_id(array($product->product_id), $line_item->quantity, $show_quantity);

  // Render the final output.
  return render(drupal_get_form($form_id, $line_item));
}
Feature request
Status

Closed: outdated

Version

1.0

Component

Developer experience

Created by

🇺🇸United States damienmckenna NH, USA

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024