Do not create and save Drupal entity (node or taxonomy term etc) in one line if you want the entity object to use

Fixing a codebase we inherited— the client switched to us because “the previous developers didn’t understand Drupal”, but most of what we observed so far it seemed our predecessors had a pretty solid understanding of Drupal sitebuilding fundamentals, and even an all-right grasp of Drupal APIs, but completely tripping over their shoelaces and crashing through perfectly good plate-glass the moment some ‘plain old’ PHP coding and programming logic is needed.

This here is the exception though— this is Drupal laying out the rake to step on.

Do not do this:

  $term = Term::create([
    'name' =>  $data['name'],
    'vid' => 'example_vocabulary',

Why? That $term will be 1 (the integer one being a PHP lazy boolean equivalant to true) provided the save succeeds (zero if somehow it does not).

You probably wanted some useful information about the term you saved, such as its term ID. Good luck!


   WARNING  Attempt to read property "tid" on int.

= null

Or more properly, but still not going to work on an integer:


   Error  Call to a member function id() on int.

Full working code would be more like this:

use Drupal\taxonomy\Entity\Term;

// [...]

  $term = Term::create([
    'name' =>  $data['name'],
    'vid' => 'example_vocabulary',

Now you can get the term ID— to get it directly note the ->value:

The other better option is:

= "4729"

But again, the main thing here is that you do not chain the ->save() method onto anything where you want a return value other than that indicating if the save were successful or not!