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
- create a node type with a multi value field
- Create a busines rules variable "Value from Entity field"
- create an action "Loop through a multi-value field variable" to loop through this variable and put some action into it
- Add a business rule to run this action (e.g. After updating Entity)
- Save a node with two or more values in the field -> rule will give the expected result
- Edit node and set only one value to the field
- 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)
| Comment | File | Size | Author |
|---|---|---|---|
| #2 | loop-through-multi-value-field-single-value-707484-1.patch | 1.08 KB | FloGe |
Comments
Comment #2
FloGe commentedComment #3
chriszz commentedThanks - #2 solves the problem for me.
Comment #4
chriszz commentedWill this patch be implemented in business rules?
Comment #5
carroll_webprog commented#2 also solved this problem for me - thank you!
Comment #6
nwom commentedSetting to Needs Review, since a patch is attached. I have not tested it myself.