Creating and configuring custom user fields

:bookmark: This guide explains how to create and configure custom user fields in Discourse, including how to add them to the signup form, user profiles, and user directory.

:person_raising_hand: Required user level: Administrator

Custom user fields allow you to collect additional information from your users beyond the standard profile fields. These fields can be displayed on user cards, user summary pages, and even retrieved using the Data Explorer plugin. This guide will walk you through the process of creating and configuring custom user fields.

Adding a user field

  1. Go to Admin > Community > User Fields (discourse.example.com/admin/config/user-fields).

  2. If you haven’t created any user fields yet, you’ll see this screen:

  3. Click the “Add user field” button to add a new field.

Choosing a field type

The field type determines the input field users will see on the signup form. Choose based on the kind of information you’re collecting:

Text field

  • Use for short questions with many possible answers (e.g., “What company do you work for?”)
  • Displays as a single-line HTML text input

Textarea

  • Use for questions that may require longer, multi-line answers (e.g., “Tell us about yourself”)
  • Displays as a multi-line HTML textarea input

Date

  • Use for collecting date values (e.g., “What is your date of birth?”)
  • Displays as a date picker input

Confirmation

Dropdown

To add options for a dropdown field:

  1. Click on the option input
  2. Type an answer and click “Create”
  3. Repeat for additional options

The completed options should look similar to this:

Multiselect

  • Use for questions where users can choose multiple answers from a set of options (e.g., “Which topics interest you?”)
  • Displays as a multi-select input
  • Options are configured the same way as dropdown fields

Setting the field name and description

  • Field Name: Appears before the input on the signup form and user profile
  • Field Description: Appears after the input to help users complete the field

:information_source: Both the field name and description are required to save a field.

Here’s how custom fields appear on the signup form:

Configuring user field options

Field Requirements

  • Optional - Optional fields may be left empty by users
  • For all users - When a field is required by all users, every account, including logged on users will be forced to fill it. This is very useful for cases such as a terms-of-service (ToS) requirement.
  • On signup - All new account will be required to fill the field.

Additionally, at the bottom of the creation form, you’ll find these preference checkboxes:

  • Editable after signup: Allows users to update the field from their profile page
  • Show on public profile: Displays the field value on the user’s summary page
  • Show on user card: Shows the field value on the user card
  • Searchable: Enables searching for users based on this field’s value in the user directory
  • Show on signup form: Controls whether the field appears on the signup form. This is automatically enabled (and cannot be disabled) when the field requirement is “For all users” or “On signup”, or when the field is not editable after signup.

Show on public profile

When enabled, the field value will be shown on the user’s profile page:

Show on user card

When enabled, the field value will be displayed on the user card:

Searchable

When enabled, you can search for users based on their custom field values:

Saving and editing fields

  1. Click “Save” to add the field to your site’s list of user fields
  2. To edit a field, click the “Edit” button next to it in the list
  3. To delete a field, click the ellipsis menu (⋮) next to it and select “Delete”

Adding custom fields to the user directory

  1. Go to the user directory
  2. Click the wrench icon:

  1. Check the custom user fields you want to display
  2. Click “Save”

The selected custom fields will now appear in the user directory table:

Last edited by @fzngagan 2025-07-17T09:12:38Z

Last checked by @hugh 2024-08-27T04:45:20Z

Check documentPerform check on document:
39 лайков
Any Plugins/Easy Mods for an Extended User Profile
Add introductory text for sign-up
Setting Security Parameters: Log-In, Read-Only, Protected Groups
Theme-Component v Plugin: What's the difference
User preference on theme components
Users self-select Category on Registration... is it possible?
Private custom user fields...?
How to add min or max values in custom fields?
User customizable theme components (how-to)
Add users to groups on signup
Announcing - Gender Pronouns Userfield on Meta
Can we implement a system for user remarks during registration for admin review?
Welcome questions on the first screen for bio
New user reviews: admin assignment and logging of progress
Add a custom per-user setting in a plugin
User Field Prompt
Custom user fields not available in api
Grant Custom Badge Upon Reading ToS
If topic info is too long, tags are cut off and create a blank line
Required vs. optional sign-up fields
Add users to groups through custom field automation
Terms of Service Checkbox
Hidden User Fields
New user filter by custom field and contact
Social Features
Where in Discourse can users publicly share PII?
Linking "static" information about member to topic posted
Using Discourse as a social media platform
Custom user post display
Disable account confirm emails when creating users via API
Links in additional fields
Clickable Social Icon Links on Profile
Extend Existing Controller?
Requiring acceptance of terms and conditions
"Fake" OAuth Provider?
Extend Existing Controller?
This freaking software works so well I can’t even
Allow users to block keywords
Customize Your Site Branding
Restrict the users to post in the groups who haven't uploaded their profile picture
Adding non-visible user custom fields to the API
Seeking Advice: making a discourse forum hyper local
Add custom fields to signup and login
Can add short message to verify? Just input phone number can sign up
Add terms when make new topic
Export custom field for users in discourse hosted forum
Customizing Sign-up and Log in
Grouping poll results by user custom field
Disclaimer for tutorials
How to add custom logic input on the signup page?
Terms of service changes in Discourse platform

По-моему, под этими заголовками отсутствуют два изображения:

Не уверен, связано ли это с темой Отсутствующие изображения на Meta.discourse.org — опубликую там тоже.

Я вижу эти изображения? (также в окне инкогнито)

1 лайк

Я не вижу эти

Но второе работает в моём цитировании.

Изменить

1 лайк

Любопытно, я вижу вторую картинку в цитате, но не в оригинальном посте ^^

1 лайк

Хм, это интересно. Думаю, скоро выйдет исправление для проблемы Missing images at Meta.discourse.org, так что, надеюсь, всё уладится. :crossed_fingers:

2 лайка

Есть ли настройка, которую мне нужно изменить, чтобы указать максимальную длину пользовательского поля? Сейчас в этом поле «Test», которое я создал как тестовое пользовательское поле, я не могу ввести даже один символ в своём профиле (даже слово «Test», как показано на скриншоте).

Мне бы очень понравился тип поля: ссылка / URL. Это возможно?

Так как URL — это текст, текстовое поле технически работает, @Vaping_Community. Однако, возможно, вы ищете дополнительные возможности, такие как валидация значений или что-то подобное.

Вы можете поискать или создать тему с тегом #feature с описанием вашей идеи. :slight_smile:

3 лайка

Есть ли планы разрешить многострочный ввод/компоновку для пользовательских полей? :folded_hands:

Обратите внимание: если вы хотите вставить ссылку в одно из пользовательских полей, необходимо использовать HTML-синтаксис!
<a href="url">текст ссылки</a>

Например, для указания на правила/политики сообщества:

1 лайк

Могу ли я сопоставить пользовательское утверждение из моего SSO в Auth0 с пользовательским полем? Сейчас пользователь вводит информацию о поле в Auth0, а затем должен ввести её повторно при регистрации. Я хотел бы, чтобы значение было перенесено автоматически, если это возможно.

Это возможно, да:

В вашей конечной точке SSO вы можете сопоставить утверждение с полезной нагрузкой, например:

const ssoPayload = {
  nonce: nonce,
  email: user.email,
  external_id: user.sub,
  username: user.nickname,
  name: user.name,
  add_groups: a_custom_group,
  'custom.user_field_1': user['https://yourdomain.com/company_id'],
  'custom.user_field_2':  [и так далее...]
3 лайка

Спасибо @dax

Есть ли способ проверить имя поля в базе данных? Например, у нас есть поле «имя», я пробовал custom.firstname, custom.first_name и custom.firstName, но ни один из них не привел к заполнению полей на экране регистрации.

Я проверил логи ошибок, чтобы подтвердить, что токены полей приходят так, как показано выше.

Разбираясь в коде глубже, это только для SSO Discourse Connect? Мы используем плагин Auth0

Синтаксис должен быть custom.user_field_x, где x — числовой идентификатор поля, отображаемый в /admin/config/user-fields/{x}/edit.

Функция сопоставления недоступна напрямую в плагине Auth0.

Тем не менее, есть варианты реализации того, что вы описываете:

  • создание компонента темы. Вы можете добавить небольшой фронтенд-скрипт, который автоматически синхронизирует пользовательское поле в Discourse со значением, уже сохранённым в Auth0. Например, когда пользователь входит в систему, а поле пустое, скрипт может вызвать защищённую конечную точку (небольшую облачную функцию), которая получит значение поля из Auth0 и обновит профиль в Discourse через API.
  • использование инструментов автоматизации. Вы также можете использовать внешние сервисы автоматизации, такие как Zapier или Make, для выполнения этой синхронизации вне Discourse. Преимущество в том, что вам не нужно писать или поддерживать код, достаточно только платить за сторонний сервис.
  • кастомная разработка. Мы можем расширить сам плагин Auth0, чтобы он нативно поддерживал сопоставление пользовательских утверждений (custom claims) с пользовательскими полями при входе, либо создать собственный плагин, работающий в паре с плагином Auth0.

Явный недостаток подхода с компонентом темы заключается в том, что вам придётся самостоятельно писать и поддерживать кастомный код, а также проявлять осторожность с точки зрения безопасности, чтобы не допустить потенциальных ошибок или уязвимостей. Честно говоря, это не решение, которое я бы рекомендовал для продакшн-сайта, подобного вашему.

Если бы я был на вашем месте, я бы склонился ко второму варианту — использованию сторонних инструментов, или рассмотрел бы возможность подачи запроса на новую функцию или запроса на кастомную разработку (в зависимости от оценки нашими менеджерами проектов) для расширения самого плагина Auth0.

Если вы заинтересованы в рассмотрении последнего варианта, мы можем продолжить обсуждение в личном порядке.

1 лайк

Интересует, есть ли более удобный способ реорганизовать длинный список полей пользователя, чем по одному кликать на маленькие стрелочки, чтобы перемещать их вверх или вниз по одному шагу за раз…? :face_with_peeking_eye:

В общем списке полей пользователя я не вижу, как отличить обязательные поля (например, «Je suis… Pays»), которые отображаются в форме регистрации, от необязательных (например, «Mes attentes»). Я что-то упускаю, или это упущение? Очень неудобно редактировать поле, чтобы узнать, является ли оно необязательным. (Не уверен, что это правильное место для такого вопроса, не знал, куда его разместить.)

Возможно, JSON, предоставляющий данные, может немного помочь. Это не совсем красиво, но вы можете посмотреть на /admin/config/user-fields.json и увидеть что-то вроде

    {
      "id": 18,
      "name": "Age",
      "description": "How old are you?",
      "field_type": "text",
      "editable": true,
      "required": false,
      "requirement": "optional",
      "show_on_profile": false,
      "show_on_user_card": false,
      "show_on_signup": false,
      "searchable": false,
      "position": 9
    },
    {
      "id": 17,
      "name": "pets",
      "description": "choose your favourite",
      "field_type": "dropdown",
      "editable": true,
      "required": false,
      "requirement": "optional",
      "show_on_profile": false,
      "show_on_user_card": false,
      "show_on_signup": false,
      "searchable": false,
      "position": 10,
      "options": [
        "cat",
        "mouse",
        "dog"
      ]
    },

Но, конечно, это не так красиво, как информация в интерфейсе.

1 лайк

Ого, это действительно гораздо удобнее для работы!
Значит, я могу просто отредактировать этот файл и всё готово? Существует ли он в таком виде на моём сервере и где его найти? :heart_eyes::heart_eyes::heart_eyes: