6

I have done:

$term = Term::create([
  'name' => 'title', 
  'vid' => 'myvocab',
])->save();

It works.

But I don't seem to be able to set the parent term.

I have tried:

$term->parent = array($parent_tid);
$term->save();

It gives an error:

InvalidArgumentException: Value is not a valid entity. in Drupal\Core\Entity\Plugin\DataType\EntityReference->setValue() (line 106 of /core/lib/Drupal/Core/Entity/Plugin/DataType/EntityReference.php).

I have also tried:

$term->parents = array($parent_tid);
$term->save();

It gives no error, but also does nothing.

In my code $term could be a new term or an existing term I've loaded, which is why I set the parent and then save it. But I can't get it to work.

Documentation for D8 is sparse. I've dug around the code in the taxonomy module, and it looks like parent is an entity reference field that accepts multiple values, but I can't work out how to set it. It looks like setting parent to array($id) should work, but I think the magic setter is breaking. Any help?

2 Answers 2

12

The correct way for a reference field is to set the property target_id:

$term->parent = ['target_id' => '2'];

All this shorter versions work too:

$term->parent = ['2'];
$term->parent = '2';
$term->parent = 2;

Also works like this:

$term->set('parent', ['target_id' => 2]);
$term->set('parent', 2);
3
  • 2
    If you like using the get/set methods another valid format would be $term->set('parent', ['target_id' => 2]);
    – gcalex5
    Dec 22, 2017 at 15:14
  • 2
    This may have changed as of 8.6.1... there was a standardization of the term parent field.
    – atwixtor
    Sep 27, 2018 at 17:50
  • 8.9.1 $term->parent = ['target_id' => $parent_id]; somehow didn't work whereas $term->set('parent', ['target_id' => $parent_id]); worked.
    – leymannx
    Dec 2, 2020 at 18:06
1

It turns out that I was doing it right after all: $term->parent = array($parent_tid). The problem was that to find $parent_tid, I was using $another_term->tid. It turns out that this is a FieldItemList, and to get the tid I have to use $another_term->tid->value. I don't know if maybe there is a better way?

2
  • 2
    For all entities it is id(), you don't need to look it up in the field: $term->id()
    – 4uk4
    Mar 28, 2017 at 15:35
  • 1
    The docs for Term class on the docs website do show all methods, and id() is one of them.
    – Kevin
    Mar 28, 2017 at 15:36

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.