Score:1

Get the value of taxonomy custom user field

gb flag

I am trying to get a taxonomy field in hook_user_insert().

user account

The logic is that if the taxonomy field is selected as none then print warning message along with a success message.

function drupal_practice_user_insert($account) {
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $brand = $user->field_add_brand->value;
  if ($brand == null) {
    \Drupal::messenger()->addWarning(t('My new custom message.'));
  }
}

The problem is that the taxonomy field value results NULL all the time.
What am I doing wrong? How can I get the taxonomy field value?

apaderno avatar
us flag
`\Drupal::currentUser()` returns the User entity for the currently logged-in user. It is not necessary to load the User entity that is created, since that is already passed to the hook in `$account`.
Priya Degwekar avatar
gb flag
@apaderno , Followed your suggestion and with that i have added getValue() in place of get() and successfully get the field value. Thanks!
id flag
Does this answer your question? [How to programatically access the value of a taxonomy term reference?](https://drupal.stackexchange.com/questions/246225/how-to-programatically-access-the-value-of-a-taxonomy-term-reference)
Priya Degwekar avatar
gb flag
Hi @cilefen, This solution is not working for me. I am getting an error of undefined method getName().
Score:0
gb flag

Ok, I figured it out! This is the solution:

function drupal_practice_user_insert($account) {

    $user = \Drupal\user\Entity\User::load($account->id());
    $brand = $user->get('field_add_brand')->getValue();
    if(empty($brand)){
        \Drupal::messenger()->addWarning(t('My new custom message.'));

    }
 }
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.