1

I would like to get all enabled variants for a product. I refer to the following question, where a method for limiting a for-loop is given:

Disabled product variant still shows in {% for %} loop

In the comments Andreas provides a way to get all enabled variants for a product:

{% set variants = craft.commerce.variants({ product: product, enabled: true }) %}

However, in my case this does not return any variants, while there are two active. Instead, it returns the following object:

object(craft\commerce\services\Variants)#2364 (3) {
  ["_events":"yii\base\Component":private]=>
  array(0) {
  }
  ["_eventWildcards":"yii\base\Component":private]=>
  array(0) {
  }
  ["_behaviors":"yii\base\Component":private]=>
  NULL
}

How can I get all the active variants for a product?

2

If you already have the product

PHP

$product = Product::find()->one();
$variants = ArrayHelper::filterByValue($product->variants, 'enabled', 1);

Twig

{% set product = craft.products.one() %}
{% set variants = product.variants|filterByValue('enabled', "1") %}

If you don't have the product

Twig

{% set variants = craft
    .commerce
    .variants
    .productId(x)
    .all() 
%}

PHP

$variants = Variant::find()
    ->productId(x)
    ->all();

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.