Accessing custom user fields via JavaScript/plugin API

Hello, I was trying to implement Our solution for blurring NSFW content - #5 by bartv - but unfortunately the code did not work anymore.
I am kind of stuck here and i couldn’t find any documentation for the discourse JavaScript API in general or how to retrieve custom user fields.

I tried adding the linked code snippet to the header.html section in my site’s theme.
The object accessible in JavaScript const user = api.getCurrentUser(); seems to contain a property custom_fields not user_fields as it is in the referenced posting.

However it is empty, or i don’t know how to properly query/fill it. I’m getting the feeling i would need an actual Ruby plugin to access this data.

I would really appreciate any help on this issue, or guide how to specifically get the same functionality working again.
The feature i need is adding a custom css-class to the body depending on a custom user field.

Thanks for reading o/

If you look at the .json output of a user profile, you’ll see the user_fields record (like, except there are no custom fields here). That’s where the user fields that you add in the UX are (they are actually a special kind of user_custom_field. The user_custom_fields do not seem to be in the user record in a topic stream. I’m not sure if they were once there and are now gone (this would probably be a bug). You need to make sure that your user fields are visible in those settings (show on user card, maybe?).

From what I see now, you need to create a plugin that will add those custom fields to the serializer.

If you could use groups instead of your custom user field, you might solve your problem.

1 Like

That’s where the user fields that you add in the UX are (they are actually a special kind of user_custom_field

I see, that explains the variable naming. Thank you.

I think the /u/user.json endpoint only exposes public fields since it is publicly accessible. Due to the nature of the issue, i doubt people would want their NSFW preferences exposed on their user card. Thus i will look into using groups as a workaround first :smiley:

1 Like