Getting user profile custom field via JS

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 me gusta

You want something like

$.ajax("/session/current").then(function(result) {
  console.log(result.current_user.custom_fields);
});
2 Me gusta

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 Me gusta

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

3 Me gusta

got it thanks! :smile:

3 Me gusta

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 Me gusta

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 Me gusta

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

https://github.com/xfalcox/discourse-signatures/blob/1ff4e7e1d57eed825febdbd58980a73bef03cb6b/plugin.rb#L19

1 me gusta

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 me gusta

Por alguna razón, no puedo ver los campos de usuario personalizados en la consola que agregué en la sección Administrador > Personalizar > Campos de usuario.

He puesto lo siguiente en un plugin:

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

Cuando miro en el objeto de usuario, veo un objeto en blanco en la entrada custom_fields. Cuando lo cambio a console.log(user.custom_fields); todavía muestra un objeto en blanco.

El usuario actual tiene tres campos personalizados completos, he agregado las tres claves de campo, en el formato de test_topic a los campos de usuario públicos y campos de usuario del personal y, sin embargo, el objeto todavía aparece vacío en la consola.

Le he preguntado a ChatGPT (¡lol!) y no parece estar ayudándome.

¿Alguna sugerencia sobre lo que podría estar sucediendo?

ACTUALIZACIÓN: Creo que un problema fue que estaba usando custom_fields y ahora parece estar bajo la etiqueta user_fields, como se indica aquí:

Sin embargo, parece que solo me muestra el valor del campo de usuario personalizado y un número para la clave, en lugar de la clave personalizada que ingresé en Administrador > Personalizar > Campos de usuario.

1 me gusta

Este componente temático podría ser de interés dependiendo de lo que busques hacer con el campo de usuario.

Este añade la ocultación de publicaciones con una especie de palabras vigiladas por el usuario.

Ver el código fuente puede darte ideas.

1 me gusta

Solo estoy tratando de crear un pequeño componente temático que se asegure de que los campos de usuario personalizados que agrego en administración > personalizar > campos de usuario sean:

  1. Agregados a i18n traducible para que pueda personalizar el texto de ellos en la sección de administración > personalizar > texto
  2. Agregados como claves de interpolación para que pueda usarlos como %{key} en la sección de administración > personalizar > texto

Básicamente, estoy tratando de resolver mi propio problema que publiqué aquí:
https://meta.discourse.org/t/create-and-configure-custom-user-fields/113192/55

Pero no pude pasar la primera parte de obtener la combinación clave/valor de los campos de usuario en el objeto de usuario.

¡Le echaré un vistazo a lo que has agregado, gracias!

1 me gusta

Soy muy nuevo y estoy aprendiendo sobre la marcha. No puedo decirlo con seguridad, pero si para las traducciones de idiomas hay 2 complementos que hacen traducciones.

Y

Me disculpo si he entendido mal lo que intentas lograr si es incorrecto.

1 me gusta