Score:0

Right way to print logged in user custom fields

in flag

What is the right way to get the field value for the account used from the currently logged-in user and print it in a template file, for example a block or a page template file?

I was trying to use the following code, but it doesn't work.

use Drupal\Core\Entity\EntityTypeManager;
use Drupal\user\Entity\User;

$user_id = \Drupal::currentUser()->id();
$user_entity = \Drupal::entityTypeManager()->getStorage('user')->load($user_id);
$variables['field_custom'] = $user_entity->field_custom->value;

In the template file, I am using this code.

{{ field_custom }}

Since the field custom is available, how can I print other field properties when the field is an entity reference field to a taxonomy term?

NataN avatar
in flag
Nope, because this example becames value from node. I want the user fields value globally to use in Blocks and Page Twigs.
ru flag
It doesn't matter if this comes from a node or a user. _Every_ entity reference field works this way
NataN avatar
in flag
Im so sorry but its does not make any sense to me, I wanna print values from current user profile, not from node. Its should have a simple query. Even that, I have tryed use the example from indicate link, but no success. I have changed the {{ node.field.entity }} to {{ user.field.entity }} but no works. Also I have printed {{ user.displayname }} with success, now I need to print custom user fields.
Kevin avatar
in flag
It doesn't matter that the linked question says "node" - check the docs. Accessing entity fields and their values is all the same.
NataN avatar
in flag
I appreciate all answers but you are indicating a link relationated with node entity reference, I let very clear I need print current logged-in user values on page or block templates, its have no relation with node. So I had to create a view for that as indicated in this question https://drupal.stackexchange.com/questions/291275/how-can-i-print-user-field-values-in-page-html-twig. Also, for system menus is possible to use the https://www.drupal.org/project/menu_token module using "current user" token.
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.