Programmatically update a taxonomy term $term = Term::load($_tid);
$term-&gt;field_league_id = 'ID value';
$term-&gt;Save();


I am updating the terms by the code above but it's not working. Create the term by term->Save() is works normally. Everyone had experienced with that please help.

Updated:

$term = Term::load($_tid);
$term-&gt;field_league_id-&gt;setValue($league_id);
$term-&gt;Save();


This solution is not working, it's throwing:


  Call to a member function setValue() on a non-object in..


At the top, I declared ref. already.

use Drupal\taxonomy\Entity\Term;


The code for create new taxonomy is working fine, but not for updating.

$term = Term::create([
            'name' =&gt; $league-&gt;caption,
            'vid' =&gt; 'league',
            'field_league_id' =&gt; $league_id,
            'field_league_code' =&gt; $league-&gt;league,
            'field_league_year‎' =&gt; $league-&gt;year,
            'field_league_numberofteams' =&gt; $league-&gt;numberOfTeams,
        ]);

        $term-&gt;Save();
$term = Term::load($_tid);
$term-&gt;field_league_id-&gt;setValue('ID value');
$term-&gt;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.