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));
}
CommentFileSizeAuthor
#1 commerce-n1411620.patch1.33 KBdamienmckenna

Comments

damienmckenna’s picture

Status: Active » Needs review
StatusFileSize
new1.33 KB

The code above as a patch file.

rszrama’s picture

In Commerce, any function ending in _form() is expected to actually return a form array, not a rendered form. Any reason you didn't just make a simpler form builder resembling the trimmed down add to cart function we made?

rszrama’s picture

Category: task » feature
Status: Needs review » Needs work

(I should've updated the status.)

jsacksick’s picture

Issue summary: View changes
Status: Needs work » Closed (outdated)