web-dev-qa-db-ja.com

数量を入力してカートに追加フォームをプログラムで作成する方法は?

プログラムで、数量を入力し、デフォルトを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);

しかし、値1の非表示フィールド数量を取得するだけで、数量値を変更できません。静的な値の代わりに数量を入力するにはどうすればよいですか?

3
lovesx

面白い。私はこれをするつもりはなかったでしょう。 commerceモジュールでのクイック検索により、この例が生成されました:

<?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);
?>

つまり、これを行うことができます:

<?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);
?>

そして、それが数量にどのように影響するかを確認します(適切なフィールドになります)。また、コアモジュールがフィールドの表示/非表示をどうするかを決定するために使用する$ cart_contextもありません。

1
joshmiller