CommonDocs.org

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).

1function loadUserFieldValue($userId, $fieldName){
2    try{
3        $db = Factory::getContainer()->get('DatabaseDriver');
4        $query = $db->getQuery(true)
5                    ->select($db->quoteName('value'))
6                    ->from($db->quoteName('#__fields_values', 'fv'))
7                    ->join('INNER', $db->quoteName('#__fields', 'f') . ' ON (' . $db->quoteName('f.id') . ' = ' . $db->quoteName('fv.field_id') . ')')
8                    ->where($db->quoteName('fv.item_id') . ' = ' . $db->quote($userId))
9                    ->where($db->quoteName('f.name') . ' = ' . $db->quote($fieldName));
10        $db->setQuery($query);
11        $result = $db->loadResult();
12        return $result;
13    }
14    catch(Exception $e){
15        return null;
16    }
17}

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.

1//Get the userId of current logged in user
2$userId = Factory::getApplication()->getIdentity()->id;
3//Get filename from field
4$favColorFile = loadUserFieldValue($userId, 'favcolor');
5
6//Set default if not found
7if(!$favColorFile){
8    $favColorFile = 'blue.css';
9}
10
11//Load stylesheet with WAM
12$wa->registerAndUseStyle('favcolor', 'media/templates/site/cassiopeia/css/global/' . $favColorFile);
13
14//for testing purposes
15echo $favColorFile;

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

More in Code Snippets

Adding Custom Fields On Extension Install

Custom Fields may be useful in many Joomla extensions. They can be added by calling a custom script file upon an extension install or uninstall. The script…

Read guide
Was this guide useful?

Spotted a mistake? Select the sentence in the guide and choose “Suggest a fix”.

Comments

Found an error? instead, it reaches me faster.

No comments yet. Questions and corrections are welcome.