This pretty cool answer taught me to push new term references like this:
$node->field_tags[] = 6;
... but if that reference already exists you get a duplicate.
This isn't possible through the UI and isn't what you would usually want. The duplicates show up in the rendered view.
Here's the horrible thing I did to check for the reference I'm trying to add:
$term_refs = $node->field_tags->getValue();
$has_ref = count(array_filter($term_refs, function ($term_ref) use($tid) {
return in_array($tid, $term_ref);
}));
if (!$has_ref) $node->field_tags[] = $tid;
Is there a hasValue() method or magic PHP function I'm missing that I can use instead?
The structure of $term_refs
(the field_tags
value) looks like this:
Array
(
[0] => Array
(
[target_id] => 6
)
)
Update: Clive's solution is what I'm looking for but I couldn't get this to work. So I modified George's answer to this so I can skip existing refs:
if (in_array($tid, array_map(function ($i) { return $i['target_id']; }, $term_refs))) continue;
ArrayAccess
, wouldif (!in_array($tid, $node->field_tags)) {
do the trick?