8

After loading a node with Node::load with an existing taxonomy field abc do I add a new term and save? Something like?

  $term = Term::load(123);
  $node->get('abc')->appendItem($term );
3
  • I think $node->get('abc')->appendItem(['target_id' => 123]); would work
    – mradcliffe
    Apr 11, 2016 at 13:33
  • Strange - it seems that my approach also work... still checking.
    – Nic
    Apr 12, 2016 at 7:11
  • Yes, that is correct. The code to set the value of reference entries is very tolerant and accepts the full array with target_id and/or entity keys, a skalar with the id and an object of the term, which is then used to retrieve the id and store it in the database. But it does not make sense in your case to load the term and pass it, when later it is only used to get the id.
    – 4uk4
    Apr 12, 2016 at 16:22

2 Answers 2

6

This is the correct long form, as in the comment of mradcliffe:

$node->get('abc')->appendItem(['target_id' => 123]);

You don't need to load the term, use the term id.

You can use shorter versions:

$node->abc->appendItem(['target_id' => 123]);
$node->abc[] = ['target_id' => 123];
$node->abc[] = '123';
7
  • For the last short form, is it really '123' as a string?
    – Nic
    Apr 11, 2016 at 18:36
  • Is this documented somewhere officially? I tried to look this up on Drupal.org but without success
    – Nic
    Apr 11, 2016 at 18:37
  • You can use both, string and int. There are magic functions in the object to use the itemlist as array and the fields in the shortened version.
    – 4uk4
    Apr 11, 2016 at 18:54
  • Will this ignore duplicates? I'm prepareing an import script and an worried it will corrupt something if I run $node->abc[] = '123'; multiple times during testing
    – Nic
    Apr 12, 2016 at 9:51
  • 1
    @Rob, yes, you have to loop over the field values. You don't need to use getIterator() though, because the array interface works like a normal array and you can put the field object directly in a foreach loop
    – 4uk4
    Mar 22, 2018 at 16:50
-1

Just check the following code, its a dummy code need to be test

use \Drupal\node\Entity\Node;

$node = Node::create([
      'type'        => 'article',
      'title'       => 'Druplicon test',
    ]);
    $node->set('myterm_field', 'NEW TERM');
    $node->save();
1
  • I don't think that entity reference fields are set using a string value.
    – mradcliffe
    Apr 11, 2016 at 13:20

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.