Drupal commerce - 從代碼建立訂單


Drupal commerce 己經成為 Drupal 電子商務應用的主流了,ubercart 落伍了

Ubercart 是一個源自 Drupal5.x 世代的方案
而為了使用 Drupal7 方便的 entities,和令電子商務方案使用一個「弱品牌化」的名字,Drupal commerce 誕生了

但因為 Drupal commerce 龐大的代碼量,為了方便分散工作,代碼都打散到不同的模組,各自有他們的維護者
再加上為數不少的 dependencies 令上手的難度過大
所以 Drupal commerce kickstart 便將一個完整的電子商務網站包裝起來
只需要下載安裝,匯入範例便可以立即使用了

這次的開發和前一次類似,從代碼建立將貨物放到訂單:

<?php
$cp
= commerce_product_new($type);
$cp->is_new = TRUE;
$cp->revision_id = NULL;
$cp->uid = $user->uid;
$cp->status = 1;
$cp->language = LANGUAGE_NONE;   
$cp->created = $cp->changed = time();
$cp->sku = 'shirt_od' . $extras['title'] . drupal_hash_base64(microtime());
$cp->title = $cp->sku;
?>

使用

<?php
 field_attach_submit
()
?>
儲存貨品,便可以觸發相對應的 hooks 了:
<?php
$price
= array(LANGUAGE_NONE => array(0 => array(
   
'amount' => $price * 100,
   
'currency_code' => commerce_default_currency(),
)));
$form_state['values']['commerce_price'] = $price;

// custom fields
$form_state['values']['field_quantity']     = array(LANGUAGE_NONE => array(0 => array('value' => $quantity)));
$unit_price = array(LANGUAGE_NONE => array(0 => array(
   
'amount' => $unit_price * 100,
   
'currency_code' => commerce_default_currency(),
)));
$form_state['values']['field_unit_price']     = $unit_price;
field_attach_submit('commerce_product', $cp, $form, $form_state);

commerce_product_save($cp);
?>

購物車:

<?php
$order
= commerce_order_new($uid, 'cart');
commerce_order_save($order);

$line_item = commerce_product_line_item_new($cp, 1, $order->order_id);
// Save the line item to get its ID.
commerce_line_item_save($line_item);

// Add the line item to the order using fago's rockin' wrapper.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;

// Save the order again to update its line item reference field.
commerce_order_save($order);
?>
Google