0

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;
  • I think field classes implement ArrayAccess, would if (!in_array($tid, $node->field_tags)) { do the trick? – Clive Mar 23 '16 at 18:48
1

array_unique could solve your problem here, perhaps employing a similar solution to the one proposed in https://stackoverflow.com/questions/10408482/how-to-get-unique-value-in-multidimensional-array

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.