1

ive created custom fields in my product type.

enter image description here

then i have this code under my custom module

global $user;
$order = commerce_cart_order_load($user->uid);
if($order) {
     $line_item_list = $order->commerce_line_items["und"];
     foreach ($line_item_list as $key => $value) {
         $line_item = commerce_line_item_load($value["line_item_id"]);
         drupal_set_message('<pre>' . print_r($line_item, TRUE) . '</pre>');
     }
}

i tried to print per line item to, but i cant see my custom field in the print...

anyone experienced this?

1 Answer 1

1

You added the fields to the commerce product entity (commerce_product), not the line item entity (commerce_line_item).

That is why the fields don't show on your line item entity.

The line item entity contains a product reference field (commerce_product) referencing the associated product, you will need to inspect that to get the fields from the product.

e.g:

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
// Get product field value from line item
foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
  // If line item is a commerce product type
  if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
    // Fetch duration value on product.
    $duration = $line_item_wrapper->commerce_product->field_subscription_duration_2->value();
    // Get raw values
    // $duration = $line_item_wrapper->commerce_product->field_subscription_duration_2->raw();
    drupal_set_message($duration);
  }
}
4
  • you have point there! :) thanks.. but how come i cant print the variable $duration? it doesnt print anything.. thank you. Commented May 7, 2014 at 8:56
  • your answer was useful, i edited it a little for it to work in mine, here's my code $duration = $line_item_wrapper->commerce_product->value()->field_subscription_duration_2["und"]["0"]["value"]; thank you! Commented May 7, 2014 at 9:27
  • Glad it helped, please marked solved if suitable thanks. Note you can also use $line_item_wrapper->commerce_product->field_subscription_duration_2->raw(); to get the raw field values. Commented May 7, 2014 at 9:37
  • Use: $line_item_wrapper->getBundle() instead of $line_item_wrapper->type->value() as it could cause some issues like Unable to get the data property type as the parent data structure is not set.
    – kenorb
    Commented Sep 1, 2014 at 16:16

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.