Accessing Custom User Field Values With PHP

In my guide on custom user fields in Joomla, I show how to add custom fields to a user’s profile. By default, Joomla only allows you to use these fields to show or save information about users. If you’re a developer, you can use this to programmatically add user-specific functionality to your website. 

Scenario

Suppose you want the users of your website to be able to select a specific template variant based on their favorite color. A personalization feature. You have made 5 color variants for your site’s template. If the user selects the color red as their favorite, a stylesheet called red.css is loaded which styles all the colors on your site to be red instead of the default blue.css file. 

Remember, this is just an example. The same basic logic could apply to many functions and scenarios in other types of extensions.

Create The Field

Begin by creating the field. It should be visible in the user’s profile settings, but it’s not something that needs to be visible to the public.

Also, make sure you set the field permission for “Edit Custom Field Value” to allow for registered users, otherwise only admins will be able to edit the fields. We want everyone to be able to edit their own fields.

Make sure you have a link (menu item type: users – edit user profile) in your front-end menu for logged in users to be able to view and edit their profiles, since this is where the setting is located. It will look like the screenshot when the user goes to edit their profile.

Access The Field (My loadUserFieldValue Function)

Now that the field is there, each user can save their favorite color. We need to get the template to read this value and load the css file. If the user isn’t logged in, or it can’t find the value, it should just load the blue.css file I’m using as default.

Here is a function I wrote to load the rawvalue of the field for any given user. It looks up the field value by the user’s ID and the field’s name (not field ID).

function loadUserFieldValue($userId, $fieldName){
    try{
        $db = Factory::getContainer()->get('DatabaseDriver');
        $query = $db->getQuery(true)
                    ->select($db->quoteName('value'))
                    ->from($db->quoteName('#__fields_values', 'fv'))
                    ->join('INNER', $db->quoteName('#__fields', 'f') . ' ON (' . $db->quoteName('f.id') . ' = ' . $db->quoteName('fv.field_id') . ')')
                    ->where($db->quoteName('fv.item_id') . ' = ' . $db->quote($userId))
                    ->where($db->quoteName('f.name') . ' = ' . $db->quote($fieldName));
        $db->setQuery($query);
        $result = $db->loadResult();
        return $result;
    }
    catch(Exception $e){
        return null;
    }
}Code language: PHP (php)

You should be able to use that function to get the value of any custom user field provided you know the name of the field and the user id you’re looking for. You can basically use this function anywhere, or add it to a helper class for your extension!

Finish Scenario

Now that I have a means of getting the field values, all I need to do is find the current logged in user’s ID, get the stylesheet name from the value, and load the stylesheet with Joomla’s web asset manager at the top of my template’s index.php file.

//Get the userId of current logged in user
$userId = Factory::getApplication()->getIdentity()->id;
//Get filename from field
$favColorFile = loadUserFieldValue($userId, 'favcolor');

//Set default if not found
if(!$favColorFile){
    $favColorFile = 'blue.css';
}

//Load stylesheet with WAM
$wa->registerAndUseStyle('favcolor', 'media/templates/site/cassiopeia/css/global/' . $favColorFile);

//for testing purposes
echo $favColorFile;Code language: PHP (php)

Now, when I login as any user, I can set my favorite color and it loads the css file accordingly.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments