If I want to access something outside the scope of a widget that only has access to the User object, how would I do? I am specifically trying to show a custom_field beside the user’s name in a post.
I was thinking of doing something like this in poster-name widget:
The poster-name widget has access to the entire post as attrs. If you want to attach a new widget within it, you can just pass along attrs and get access to everything.
Custom fields in particular are quite commonly needed in plugin widgets, so you can just access them like `attrs.userCustomFields.
Remember to make sure you whitelist the custom field if you want it accessible in your plugin:
That should definitely work. Just to confirm, you were viewing the user as a staff user right? That API only makes the custom field visible for staff users.
Ya, I have it in the public_user_custom_fields site setting as well. Perhaps I am misunderstanding userCustomFields. The field in question is created under customization > user fields and the user can fill it in under their preferences.
Custom fields are a database structure originally built for plugins to store meta data associated with various things, including users. Originally the only way to create/update them was via a plugin.
Later we added that custom field admin section to make it easier for discourse admins to add forms and capture certain values. It uses the same back end as the plugin system, but you need to use the database name to access them.
It might be a good idea to accept either name, now that you mention it. I doubt there would be a conflict if we searched by name first and if not then value.
Ok, thanks. So for now the best way to access the UserCustomField in the widget is to just whitelist the user_field_X name in site settings.
Otherwise, in the plugin.rb I would need to do something along the lines of, find UserField with name “myCustomField”, get the id and then whitelist user_field_<id> somehow without site settings. Obviously possible but maybe just easier to look up the user field number and do it in site settings.
I had to re-check everything and found a bug on my part… This code works for me… Example is getting last_seen_at from user object. Would be fine for highlighting online users…
Thanks for this great project!
post_serializer.rb
attributes :post_number,
:user_last_seen_at,
def user_last_seen_at
object.try(:user).try(:last_seen_at)
end