2

I'm working on a plugin to calculate price based on width and height but struggling to get the product type of each product into the 'onPopulateLineItem' event.

So far, I've looked into the purchasables and lineItems arrays to get the information, and although I can see the typeId under the $event array, I just can't get this value.

Can anyone point me in the right direction for this please?

** UPDATE **

I've managed to get something with the below, but this feels really hacky. Is there a better way I should be doing this?

$lineItem = $event->params['lineItem'];
echo $lineItem['snapshot']['product']['typeId'];
0

100% untested, but I'd probably go through the purchasable to get the product type. Something like this should work:

$lineItem = $event->params['lineItem'];
$purchasable = $lineItem->getPurchasable();
$variant = $purchasable->getProduct();
$productType = $variant->getType();

$productType will be of type commerce\models\Commerce_ProductTypeModel.

1
  • 1
    Excellent, I'll give that a go. I tried going through the Purchasable array but not as above. Definitely looks more like what I should be doing. Thanks! – JonnyT Aug 24 '17 at 18:36
2

Very minor change to Brad's approach, and with a bit more checking to avoid issues like the product being deleted while the code is looking in that direction, etc. (based on Luke's advice).

foreach ($cart->lineItems as $item)
{
    // check the purchasable has not been deleted in the meantime
    if ($item->purchasableId)
    {
        // get the variant and the actual product so we can get to custom fields
        $variant = $item->purchasable;

        // If there is no product associated with this purchasable, it's a digital virtual product so just skip it
        if (!isset($variant->product))
        {
            continue;
        }

        // get the actual product element from the purchasable
        $product = $variant->product;

        // How to get a regular field on the product
        $title = $product->title;

        // How to get the product type - use handle rather than name, as this is less likely to change
        $productType = $product->type->handle;

        ...etc
    }
}

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.