Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save dreambubbler/a89b9ac5ff34facd60fc7d4c8afecc9b to your computer and use it in GitHub Desktop.
Save dreambubbler/a89b9ac5ff34facd60fc7d4c8afecc9b to your computer and use it in GitHub Desktop.
Drupal 8: Attach terms to entity programmatically
<?php
use Drupal\node\Entity\Node;
/**
* Before attaching a term(s) to a term reference field,
* Must know:
* - field_example_name: the full name of the term reference field
* - tid: the term ID(s) to attach
*
* Keep in mind that this example uses Node::load()
* but you can use any Entity::load()
* e.g. User::load(), Term::load(), etc.
*/
// Example 1: attaching a single term
$node = \Drupal\node\Entity\Node::load($nid);
// Attach only one term
$tid = 1; // The ID of the term to attach.
$node->set('field_example_name', $tid);
$node->save();
// End of Example 1 />
// Example 2: attaching multiple terms
$node2 = \Drupal\node\Entity\Node::load($nid2);
// To attach multiple terms, the term IDs must be in an array.
$multiple_tids = array(1, 2, 3); // Each is Term ID of an existing term.
$node2->set('field_example_name', $multiple_tids); // Note that field_example_name must allow multiple terms.
$node2->save();
// End of Example 2 />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment