1

I'm seeing a lot of "Invalid argument" errors in the web.log for a "Multiple Option Variant" module I have running. It seems to be working just fine on the site, but curious as to what the issue might be. Do I need to put in some "guards" in the code, and if so, what would that look like?

This is the error;

[error][yii\base\ErrorException:2] yii\base\ErrorException: Invalid argument supplied for foreach() in /httpd.www/craft/modules/multipleoptionvariantmodule/src/variables/MultipleOptionVariantModuleVariable.php:52
#0 /httpd.www/craft/vendor/craftcms/cms/src/web/ErrorHandler.php(76): yii\base\ErrorHandler->handleError(2, 'Invalid argumen...', '/httpd.www/...', 52)
#1 /httpd.www/craft/modules/multipleoptionvariantmodule/src/variables/MultipleOptionVariantModuleVariable.php(52): craft\web\ErrorHandler->handleError(2, 'Invalid argumen...', '/httpd.www/...', 52, Array)

The referenced file at looks like this—and it seems to be the foreach function that's the culprit;

namespace modules\multipleoptionvariantmodule\variables;

use modules\multipleoptionvariantmodule\MultipleOptionVariantModule;

use Craft;

class MultipleOptionVariantModuleVariable
{
     public function getUniqueVariantAttributeValues($fieldName, $variants, $onlyInStock=false) {
         $addedIds = array();
         $sizes = array();

         foreach($variants as $variant) {
             $outOfStock = (($variant->stock <= 0) && ($variant->hasUnlimitedStock == false));

             if (!$onlyInStock || ($onlyInStock && !$outOfStock)) {
                 if (isset($variant->{$fieldName}[0])) {
                     if (array_search($variant->{$fieldName}[0]->slug, $addedIds, true) === false) {
                         $sizes[] = $variant->{$fieldName}[0];
                         $addedIds[] = $variant->{$fieldName}[0]->slug;
                     }
                 }
             }
         }

         return $sizes;
    }
}

This is then how that is used in the template(s);

{% set variants = product.variants %}
{% set variantColors = craft.multipleOptionVariantModule.getUniqueVariantAttributeValues('variantColor', variants, false) %}
{% set variantTypes = craft.multipleOptionVariantModule.getUniqueVariantAttributeValues('variantType', variants, false) %}

I'd take any hints on how to convert that php functionality to pure twig too. :) That would actually be ideal.

1

You'll get that error in PHP when you try to iterate over a variable that isn't an array.

My guess is you'd be able to guard against it with something like:

if (is_array($variants)) {
    foreach($variants as $variant) {
    ...
    }
}

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.