Read profile custom fields from another template

Created on 30 July 2018, almost 7 years ago
Updated 4 January 2024, over 1 year ago

I have in my site that a user can post content in the page. Its an OpenSosial site. I want to be able to make the photo and user names directed into Profile pagessay profile/1. Currently, when user clicked on the photo its directed to procile/1 (expected) but author's name is directed into user/1. And since the variable I am looking for(thats the profile first name and last name) is not listed when I ran kint(), so someone recommends me to create a preprocess function that will add a new variable for the profile, so I can retrieve its custom fields. Would be the best approach to access profile fields from another template.

Initially, I created this is my custom.theme file

<?php

/**
* Implements hook_preprocess_HOOK() for post.html.twig.
*/
function custom_preprocess_post(&$variables) {
# todo
}
πŸ’¬ Support request
Status

Needs work

Version

1.0

Component

Code

Created by

πŸ‡΅πŸ‡­Philippines johnreytanquinco

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • πŸ‡ΊπŸ‡ΈUnited States brooke_heaton

    I'm updating to Drupal 10 and am now getting this error after using this patch:

    PHP Fatal error:  Uncaught Error: Class "Twig_Extension" not found in /app/docroot/modules/contrib/profile/src/TwigExtension/ProfileExtension.php:10
    Stack trace:
  • πŸ‡ΊπŸ‡ΈUnited States chucksimply

    I'm using this approach for displaying profile fields on my user.html.twig template.

    Create or Add this to a custom module.

    function custom_mods_preprocess_user(&$variables) {
        $user = $variables['user'];
    
        $profile_storage = \Drupal::entityTypeManager()->getStorage('profile');
    
        // Load 'profile type'.
        $business_profiles = $profile_storage->loadByProperties([
            'uid' => $user->id(),
            'type' => 'business_profile',
        ]);
        if (!empty($business_profiles)) {
            $business_profile = reset($business_profiles);
    
            if ($business_profile->hasField('field_profile_first_name') && !$business_profile->get('field_profile_first_name')->isEmpty()) {
                $variables['biz_profile_first_name'] = $business_profile->get('field_profile_first_name')->value;
            }
        }
      }
    

    Now you can call biz_profile_first_name in your user.html.twig template

    {% if biz_profile_first_name %}
        {{ biz_profile_first_name }}
    {% endif %}

    And add all subsequent fields in if statements like the above field_profile_first_name code.

    Not a perfect solution, but hopefully helps some folks.

Production build 0.71.5 2024