Drupal computed_field

Note about using compute_field.

Modules:

http://drupal.org/project/cck — with multigroup (at moment in dev)

http://drupal.org/project/computed_field

Node types:

Product

Product have one additional field Price that is required and can be only one per product.

Order

Order have noderefference Product field and its amount in Multigroup and computed field Total price.

Computed field snippet:

$total_price = 0;
foreach($node->field_order_product as $k => $v) {
  $product = node_load($node->field_order_product[$k]['nid']);
  $product_price = $product->field_product_price[0]['value'];
  $amount = $node->field_order_product_amount[$k]['value'];

  $total_price += $product_price * $amount;
}

$node_field[0]['value'] = $total_price;

 

More snippet examples: http://drupal.org/node/149228

More complex example, added field Discount and computed field Price to Multigroup, computed field Price will be calculated foreach selected product. Computed field Total price also changed to retrive price with discount.

Code snippet for Price:

foreach (array_keys($node->field_order_product) as $delta) {
  $product = node_load($node->field_order_product[$delta]['nid']);
  $product_price = $product->field_product_price[0]['value'];
  $amount = $node->field_order_product_amount[$delta]['value'];
  $discount = $node->field_discount[$delta]['value'];
  $node_field[$delta]['value'] = ($product_price * $amount) * ((100 - $discount) / 100);
}

 

Code snippet for Total Price:

$total_price = 0;
foreach($node->field_order_product_price as $order_product_price) {
  $total_price += $order_product_price['value'];
}

$node_field[0]['value'] = $total_price;