1

I have a purchasable that has a categories field. When the user visits the cart, I inspect the cart via my plugin.

I am able to see the field, but I am stumbling on how to actually check the values of the field (get the chosen categories).

MyPlugin

...

$lineItems = $cart->getLineItems();

if ($lineItems) {
    foreach ($lineItems as $lineItem) {
        error_log(print_r($lineItem->purchasable, true));
    }
} else {
    // The cart is empty.
}

...


...
[myCategoryField] => Array
    (
        [model] => 
        [column] => text
        [type] => mixed
        [label] => My Category
    )
...

If I go a step further into the field:

...
error_log(print_r($lineItem->purchasable->myCategoryField, true));

I can get something like this:

[relatedTo] => Array
    (
        [sourceElement] => 174
        [sourceLocale] => en_us
        [field] => 25
    )

This is the correct field ID, but I'm not sure how to get to the values of the category field. For example "Category A", "Category B".

Thank you for any suggestions!

2
  • 2
    I am pretty sure $lineItem->purchasable->myCategoryField returns a element criteria model, so you should be able to call ->find() on it to get the categories. May 26 '16 at 3:39
  • Thanks Luke, I am most likely misunderstanding you. When I try $lineItem->purchasable->campCategory->find() I am getting back an empty array. Maybe I'm not on the right element after all.
    – Damon
    May 26 '16 at 9:59
2

MyPlugin.php

$record = MyPluginRecord::model()->findByPk($user->id);

if ($record) {
    $field = $record->getAttributes(); // The plugin model.

    if ($lineItems) {
        foreach ($lineItems as $lineItem) {
            foreach ($lineItem->purchasable->product->myCategoryField as $category) {
                error_log($category->title); // My Category
            }
        }
    } else {
        // The cart is empty.
    }
} else {
    // Product not found in cart.
}

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.