0

I'm writing a custom Drupal Console command to import user data from a text file and create users, and as part of the process, I need to add data to a term reference field. In the case that a term in the data doesn't exist, I need to create the term and then add the new tid to the the field. I'm using the following code to create the term:

$term = Term::create([
  'name' => $member[$roster_key],
  'vid' => 'topic_area',
])->save();

The problem is the save() method only returns a boolean indicating if the save was successful, NOT the created term object. This means that now that my term has been created, I have to go do an entity query just to get the object I just created.

Is there a simple way to get the just-created term in my code above, or do I really have to do a separate query?

1

Term::create() returns the entity that the save() method gets called on. So what you want to do is save that entity to a var before calling the save() method on it.

$term = Term::create([
  'name' => $member[$roster_key],
  'vid' => 'topic_area',
]);
$term->save();

//Retrieve the tid of the new term
$term->tid->getValue();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.