Attach terms to another entity programmatically

Tutorial Goal

Lesson Goal:

Implementation Method

D7

D8

  1. Load the node or user object.

  2. Then assign a term ID to the appropriate field.

  3. Save the node or user object.

FieldableEntityInterface::set()

In Drupal 7 you can only attach term reference fields to Content Types and Users. In Drupal 8 you can attach term reference fields to any entity type.

D7 Code

Place the following in lotus.module

function lotus_attach_term() {
  $node = node_load($nid);  // $nid is the node id of the node to update.

  // field_example_term_reference: is the field name of a term reference field attached to your content type.
  // 4: is the term ID you want to assign to the node.
  $node->field_example_term_reference[$node->language][][‘tid’] = 4;
  node_save($node); // Save the changes.
}

D8 Code

Place the following in lotus.module

<?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 />

Gist Link

https://gist.github.com/dreambubbler/a89b9ac5ff34facd60fc7d4c8afecc9b

Contact supportStill need assistance? Contact Acquia Support