Andrew Fletcher published: 23 June 2022 1 minute read
How do you retrieve a taxonomy term tid value from it's name?
In this situation, use the loadByProperties function. Load the taxonomy term and then reset the array.
Note, reset - to set the internal pointer of an array to its first element.
See as follows:
/**
* Get the taxonomy term object by the name
*
* @param string $term_name Vocabulary term.
*
* @return any Term.tid
*/
public function taxonomyTermByName($term_name)
{
if (is_null($term_name)) {
return null;
}
$terms = \Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadByProperties(['name' => $term_name]);
$term = reset($terms);
return $term->tid->value;
}
The return value here could be $term. Or in this instance, when calling the function I wanted to always retrieve the term.tid value.
Related articles
Andrew Fletcher
•
19 Apr 2024
Extending a Contrib Module's Configuration in Drupal 10: A Case Study with Sitewide Alert
Extending the functionality of a contrib module in Drupal can enhance its usefulness without altering the original codebase. This article provides a step-by-step guide on how to add custom configuration options to an existing contrib module, using the sitewide_alert module as an example. We will...
Andrew Fletcher
•
18 Apr 2024
LogicException: Form errors cannot be set after form validation has finished
When receiving a logic error such asLogicException: Form errors cannot be set after form validation has finished. in Drupal\Core\Form\FormState->setErrorByName() (line 1104 of /var/www/html/project/core/lib/Drupal/Core/Form/FormState.php).This error "LogicException: Form errors cannot be set...
Andrew Fletcher
•
09 Apr 2024
Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException
Adding a new service to a custom module and the following error greeted me:The website encountered an unexpected error. Try again later.
Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "summaries.reference_node". in...