3

I want to programmatically create an add to cart form with quantity input and default as 1. I tried to use the code:

$form_id= commerce_cart_add_to_cart_form_id(array($product_id));  
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1);  
$line_item->data['context']['product_ids'] = array($product_id);
$form = drupal_get_form($form_id, $line_item);

But it just get a hidden field quantity with value 1 and I cannot change the quantity value. How can I get a quantity input instead of the static value?

1 Answer 1

1

Interesting. I would have never thought to do this. A quick search in the commerce module produced this example:

<?php
// line 2649 of commerce_cart.module

// Extract the drupal_get_form() arguments array from the element.
$arguments = $element[$key]['#arguments'];

// Add the display path and referencing entity data to the line item.
if (!empty($entity_uri['path'])) {
  $arguments['line_item']->data['context']['display_path'] = $entity_uri['path'];
}

$arguments['line_item']->data['context']['entity'] = array(
  'entity_type' => $context['entity_type'],
  'entity_id' => $entity_id,
  'product_reference_field_name' => $field_name,
);

// Update the product_ids variable to point to the entity data if we're
// referencing multiple products.
if (count($arguments['line_item']->data['context']['product_ids']) > 1) {
  $arguments['line_item']->data['context']['product_ids'] = 'entity';
}

// Replace the array containing the arguments with the return value of
// drupal_get_form(). It will be rendered when the rest of the object is
// rendered for display.
$output[$field_name][$key] = drupal_get_form($arguments['form_id'], $arguments['line_item'], $arguments['show_quantity'], $cart_context);
?>

Which means you could do this:

<?php
$product_id = 1;
$form_id= commerce_cart_add_to_cart_form_id(array($product_id));  
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1);  
$line_item->data['context']['product_ids'] = array($product_id);
$form = drupal_get_form($form_id, $line_item, true);
dpm($form);
?>

And you will see how it affects the quantity (makes it become a proper field). You're also missing the $cart_context that the core module uses to determine what to do with displaying/hiding fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.