0

I'm trying to get the dimensions(length,width and height) and weight of all products in an order.

The event that I'm using is checkout_submit_all_after.

In observer I have this code.

$order = $observer->getEvent()->getOrder();
$orderItems = $order->getAllItems();
    $dimensions = array();
    $weight = 0;
    foreach ($orderItems as $item) {
          $dimensions[]=array('weigth'=>$item->getData('weight'),'length'=>$item->getData('ts_dimensions_length'),'width'=>$item->getData('ts_dimensions_width'),'height'=>$item->getData('ts_dimensions_height'));
           $weight += ($item->getData('weight') * $item->getQty());
           $this->logger->info("weight: ".$weight);
     }

     $encodedData =  $this->_jsonHelper->jsonEncode($dimensions);
     $this->logger->info("Dimensiones: ".$encodedData);

When I print weight, I'm getting 0, I found that it takes the value of the variable initialized and never gets the total weight of all products.

And when I print the array in json form, I get this:

Dimensiones: [{"weigth":"2.0000","length":null,"width":null,"height":null}]

The product weight is correct, but it's just printing one product, even if there are more than one product in cart. The dimensions are always null, I never get the actual values of the dimensions. What am I doing wrong?

Greetings!

2

Try the following way:

/** @var \Magento\Sales\Model\Order $order */
$order = $observer->getEvent()->getOrder();
$orderItems = $order->getAllItems();
$dimensions = [];
$weight = 0;
foreach ($orderItems as $item) {
    $product = $item->getProduct();
    $dimensions[] = [
        'weigth' => $product->getData('weight'),
        'length' => $product->getData('ts_dimensions_length'),
        'width' => $product->getData('ts_dimensions_width'),
        'height' => $product->getData('ts_dimensions_height')
    ];
    $weight += ($product->getData('weight') * $item->getQty());
}
| improve this answer | |
  • Hello, Thank you! I'm getting the dimensions now, but $weight is still 0 when I print it out of the foreach. – Oscar Vazquez Dec 23 '19 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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