The "Loop through a multi-value field variable" action does not work as expected if the source field of the variable contains only one value.

How to reproduce

  1. create a node type with a multi value field
  2. Create a busines rules variable "Value from Entity field"
  3. create an action "Loop through a multi-value field variable" to loop through this variable and put some action into it
  4. Add a business rule to run this action (e.g. After updating Entity)
  5. Save a node with two or more values in the field -> rule will give the expected result
  6. Edit node and set only one value to the field
  7. Save node -> Rule seems not to work.

After doing point 7 you will find
Warning: Invalid argument supplied for foreach() in Drupal\business_rules\Plugin\BusinessRulesAction\LoopThroughFieldVariable->execute() (line 328 of web/modules/contrib/business_rules/src/Plugin/BusinessRulesAction/LoopThroughFieldVariable.php)
in the recent log messages

Assumed source of the problem

in line 27 and following of /src/Plugin/BusinessRulesVariable/EntityFieldVariable.php the value will be set to a non array value if we have only one value in the field

if (count($value) === 1) {
      if (isset($value[0]['value'])) {
        $value = $value[0]['value'];
      }
      elseif (isset($value[0]['target_id'])) {
        $value = $value[0]['target_id'];
      }
      else {
        $value = NULL;
      }
 } else
{
      $arr_value = [];
     ...

so on "Loop through a multi-value field variable" there will be no array too loop through.

Solution

Use fields cardinality to check if we need an array for the value or not
patch attached (seems to work on the first glance)

Comments

FloGe created an issue. See original summary.

FloGe’s picture

chriszz’s picture

Thanks - #2 solves the problem for me.

chriszz’s picture

Will this patch be implemented in business rules?

carroll_webprog’s picture

#2 also solved this problem for me - thank you!

nwom’s picture

Status: Active » Needs review

Setting to Needs Review, since a patch is attached. I have not tested it myself.