Drupal - Programmatically update a taxonomy term

$term = Term::load($_tid);
$term->field_league_id->setValue('ID value');
$term->Save();

Additional info (requested in comments):

If you print out the object, you'll see that fields use the class core/lib/Drupal/Core/Field/FieldItemList.php.

By browsing through the methods, you'll see a few functions for interacting with the FieldItemList object, such as setValue(),

When I'm developing in Drupal 8, in order to learn the API, I use the

dump() function a lot to see what type of object I'm dealing with, and to inspect it's methods.

dump($term); die();

In fact, in my settings.local.php file I have an include

include 'my_settings.php';

and in there I have this function:

function nprint($obj) {
  dump($obj);
  die();
}

This is something I've been using for years to inspect objects. Now that drupal is much more object-oriented, printing out objects to find what class they use is essential.

Another essential tool for me is using an editor that allows searching by file name (I use the free software Aptana Studio 3).

So if you see you're dealing with a "FieldItemList", you can do "command + t" to search by file name and type in "FieldItemList". This saves a lot of web-based research. And it helps you learn the code base.

enter image description here


Here is a simple example:

$term = \Drupal\taxonomy\Entity\Term::load($tid);
if (!empty($term)) {
  $term->field_league_id = 123; // For multivalue fields, use array().
  $term->save();
}