Getting user profile custom field via JS

AI-generated summary

The discussion revolves around accessing custom user fields in Discourse via JavaScript. dleung initially asks how to retrieve user profile custom fields using $.ajax("/session/current"). zogstrip provides the correct syntax, but dleung still faces issues accessing the attribute.

zogstrip points out that custom fields need to be whitelisted using the public_user_custom_fields site setting. Nuck and jimkleiber also face similar issues and eviltrout and eviltrout confirm that the approach should work.

Falco provides an alternative solution, but Nuck expresses concerns about performance. Falco responds, and eviltrout offers further guidance.

jimkleiber shares their experience and ultimately finds that the custom fields are stored under the user_fields label, not custom_fields. Heliosurge shares theme components that might be helpful, and jimkleiber explains their goal of creating a theme component to make custom user fields translatable.

Heliosurge suggests plugins that might be useful for language translations.

Hi,

I’m wondering if it is possible to retrieve user profile custom fields in our customized header using something like this:

$.ajax("/session/current").then(function (json) { 
    console.log(json.custom.user_field_4);
}

What would be the correct syntax?
Thanks!

1개의 좋아요

You want something like

$.ajax("/session/current").then(function(result) {
  console.log(result.current_user.custom_fields);
});
2개의 좋아요

Thanks, how do I get to the attribute?
console.log(result.current_user.custom_fields); yields an object,
i also tried:
result.current_user.custom_fields.my_field_name
and
result.current_user.custom_fields.user_field_4
they all return “undefined”

2개의 좋아요

You will need to whitelist the custom fields you want using the “public_user_custom_fields” site setting.

3개의 좋아요

got it thanks! :smile:

3개의 좋아요

Is this still accurate? I’ve added pro_expires_at as a custom field on my user (User.find('nuck').tap { |u| u.custom_fields['pro_expires_at'] = 5.weeks.from_now.to_i }.save) and stuffed that into public_user_custom_fields in the site settings panel, but I’m just not seeing it in the preload data?

2개의 좋아요

It definitely should still be working. We haven’t removed it and some plugins rely on it to work.

What preload info are you looking at? Viewing a user’s profile?

currentUser and the custom_user_fields attribute that the PostSerializer says should be present on serialized Post objects

It should definitely work if it’s public_user_custom_fields – I know we’re using this feature on some plugins and the data is indeed being displayed properly. Maybe try restarting your dev server? Does it appear in the JSON request?

2개의 좋아요

If you want a custom_user_field on the post object you can do this:

1개의 좋아요

public_user_custom_fields in the admin panel, right? Not some setting elsewhere?

I was actually developing against our staging server which rebuilds the docker every time so I’m certain it was restarted (and then some). I’ll look at the JSON request this weekend and see if I can pin this down.

Wouldn’t this cause an N+1 query? Is there any solid documentation on the whole custom field system somewhere? I didn’t realize you could register the custom field type or append to serialized_current_user_fields

I don’t think so, because the serializer already has the user object, is just a matter of including it in the payload. I can be wrong, tough.

Nope, but there are plenty of opensource plugins and the Discourse source code itself.

I found it trough other plugins code too.

Right, public_user_custom_fields in the admin panel. Those fields should end up in the JSON request. I’d double check there. Without a development environment your life is going to be a lot harder, as the next step would be to go into the code and add Rails.logger.info to try and figure out why those fields are not being passed through when they should.

1개의 좋아요

어떤 이유에서인지, 관리자 > 사용자 정의 > 사용자 필드 섹션에서 추가한 사용자 정의 필드를 콘솔에서 볼 수 없습니다.

플러그인에 다음 코드를 넣었습니다:

<script type="text/discourse-plugin" version="0.8.42">
   const user = api.getCurrentUser();
   console.log(user);
</script>

사용자 객체를 살펴보니 custom_fields 항목 아래에 빈 객체가 표시됩니다. console.log(user.custom_fields);로 변경해도 여전히 빈 객체가 표시됩니다.

현재 사용자는 세 개의 사용자 정의 필드가 채워져 있으며, test_topic 형식으로 해당 세 가지 필드 키를 모두 public user custom fields와 staff user custom fields에 추가했는데도 콘솔에서 객체는 여전히 비어 있습니다.

ChatGPT에게 물어봤지만(ㅋㅋ) 도움이 되지 않는 것 같습니다.

무슨 일이 일어나고 있는지 제안이 있을까요?

업데이트: 문제 중 하나는 제가 custom_fields를 사용하고 있었던 것 같고, 이제는 이 링크에 나와 있듯이 user_fields 레이블 아래에 있는 것 같습니다:

그러나 사용자 정의 필드의 값과 키에 대한 숫자만 표시되고, 관리자 > 사용자 정의 > 사용자 필드에서 입력한 사용자 정의 키는 표시되지 않습니다.

1개의 좋아요

사용자 필드를 어떻게 활용하고자 하는지에 따라 다음 테마 컴포넌트가 유용할 수 있습니다.

이 컴포넌트는 일종의 사용자 감시 단어를 통해 게시글을 숨기는 기능을 추가합니다.

소스 코드를 살펴보면 아이디어를 얻을 수 있습니다.

1개의 좋아요

주로 커스텀 유저 필드를 admin > customize > user fields에 추가했을 때, 해당 필드가 다음과 같은 조건을 만족하는 작은 테마 컴포넌트를 만드는 데 집중하고 있습니다:

  1. 번역 가능한 i18n에 추가되어 admin > customize > text 섹션에서 텍스트를 커스터마이즈할 수 있도록 하는 것
  2. 보간(interpolation) 키로 추가되어 admin > customize > text 섹션에서 %{key} 형태로 사용할 수 있도록 하는 것

기본적으로 제가 여기에 게시한 제 문제를 해결하려는 것입니다:
https://meta.discourse.org/t/create-and-configure-custom-user-fields/113192/55

하지만 유저 객체에서 유저 필드의 키/값 조합을 가져오는 첫 번째 단계에서 막혀서 진행하지 못했습니다.

추가하신 내용을 확인해 보겠습니다. 감사합니다!

1개의 좋아요

저는 아직 초보라서 하면서 배우는 중입니다. 확실하진 않지만, 언어 번역을 위해 번역을 수행하는 플러그인이 2개 있는 것 같습니다.

그리고

혹시 제가 여러분이 이루고자 하는 일을 잘못 이해했다면 죄송합니다.

1개의 좋아요