How do I access Custom Fields in a theme component?

In ‘Our solution for blurring NSFW content’, I used the following bit of code to access the value of a User Field. This seems to no longer work - the u.custom_fields does not contain any data anymore:

var u = Discourse.User.current();
if (u.custom_fields.user_field_2) {
    $('body').addClass('nsfw-always-show' );
}

I just updated to latest and tested in safe mode but the issue remains:

Did something about this interface change? What is the recommended method for accessing user fields?

I tested this on latest, and in safe-mode with all plugins and themes disabled.

5 Likes

You could try something like this:

<script type="text/discourse-plugin" version="0.8.27">
let currentUser = api.getCurrentUser();

if (currentUser) {
        api.container.lookup('store:main').find('user', currentUser.username).then((user) => {
        console.log('user', user.user_fields);
    });
}
</script>

See Using the PluginAPI in Site Customizations for details about the "text/discourse-plugin" script type.

11 Likes