0

I have a field that is a checkbox with multiple values... I'm trying to do an evaluation in a condition plugin where I'm checking against the checked values. For a boolean field, the syntax is:

$value = $this->getContextValue('node')->field_news_filter_menus->value;

Since field_news_filter_menus is a checkboxes field, I need to get the array of checked values. These all return null:

$this->getContextValue('node')->field_news_filter_menus->list->values;
$this->getContextValue('node')->field_news_filter_menus->values;
$this->getContextValue('node')->field_news_filter_menus->list;

PHPstorm xdebug says the path is

$this->getContextValue('node')->field_news_filter_menus->list[0]->value;

But null is returned for that also. I can see the values in xdebug that follow a path as

$this->getContextValue('node')->field_news_filter_menus->list[0]->values

and see an expected value, but that path also returns null.

What is the syntax for getting that array list?

1 Answer 1

1

Original Answer

The proper way to access field values is $entity->get('my_field')->getValue() in your case this will return an array like:

Array(
  0 => Array(
    'value' => 'value1'
  ),
  1 => Array(
    'value' => 'value2'
  ),
  2 => Array(
    'value' => 'value3'
  ),
  // And so on as many values your field has.
)

Also you can check if the field is empty by calling $entity->get('my_field')->isEmpty(). Calling only your field like $entity->get('my_field') will NOT return the field value but the field instance. Calling for an unexisting field will throw a runtime exception.

UPDATE

To check if the value exists you can either iterate over the array or do something like this

$arr = [
  0 => [
    'value' => 'value1',
  ],
  1 => [
    'value' => 'value2',
  ],
  2 => [
    'value' => 'value3',
  ],
];

$arr = array_map(function ($v) {
  return $v['value'];
}, $arr);

assert(in_array('value2', $arr, TRUE), 'Assert that contains value2');
assert(in_array('other', $arr, TRUE), 'Assert that contains other. This will fail');

You can try it here.

3
  • Yes, that is exactly as it is returned. Thanks... I need to know if a value is in that array. So, is 'value2' in that array?
    – shelane
    Commented Mar 20, 2020 at 19:17
  • You are going to have to write a foreach and check the value that way. Commented Mar 21, 2020 at 17:06
  • Yeah foreach, array_map, array_reduce pick your flavor.
    – d70rr3s
    Commented Mar 21, 2020 at 23:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.