Представляем шаблоны форм

:star: Эта функция больше не находится в экспериментальной стадии!

Подробнее о функции и о том, как использовать её в вашем сообществе, можно узнать здесь: Creating form templates

Привет, сообщество Discourse Meta!

Мы рады представить новую экспериментальную функцию — шаблоны форм. С её помощью вы можете внедрить структурированную форму с валидацией данных в процесс создания тем.

multiple_form_templates

Включение функции

Функция скрыта за глобальным экспериментальным флагом. Чтобы включить её, просто активируйте настройку сайта experimental_form_templates в разделе :wrench: Админ ▸ Настройки.

Управление шаблонами

Шаблоны форм можно создавать, редактировать и удалять в разделе :wrench: Админ ▸ Настройка ▸ Шаблоны (/admin/customize/form-templates/).

Там вы увидите таблицу со списком шаблонов, существующих на форуме. Вы можете редактировать, удалять и просматривать любой существующий шаблон или создавать новые. В таблице также отображаются категории, в которых каждый шаблон в данный момент активен.

Шаблоны определяются в структуре YAML. Вы можете ввести его вручную или воспользоваться кнопками «Добавить» вверху, которые добавят пример кода YAML в конец файла, определяя определённый тип ввода.

Вот полный пример YAML со всеми типами полей:

- type: input
  id: name
  attributes:
    label: "Полное имя"
    placeholder: "Например, Иван Иванов"
    description: "Как ваше полное имя?"
  validations:
    required: true
    minimum: 2
    maximum: 100
- type: textarea
  id: introduction
  attributes:
    label: "Введение"
    placeholder: "Краткое введение"
    description: "Напишите краткое введение о себе"
  validations:
    required: true
    minimum: 10
    maximum: 500
- type: dropdown
  id: fav-animal
  attributes:
    label: "Любимое животное"
    description: "Выберите ваше любимое животное"
    none_label: "Выберите вариант"
  choices:
    - "Собака"
    - "Кошка"
    - "Другое"
  validations:
    required: true
- type: multi-select
  id: comm-channel
  attributes:
    label: "Каналы связи:"
    description: "Выберите предпочтительные каналы связи:"
    none_label: "Выберите вариант"
  choices:
    - "Электронная почта"
    - "Телефон"
    - "Мессенджер"
- type: upload
  id: cat-photo
  attributes:
    label: "Фото кошки"
    description: "Отправьте фото вашей кошки (или любой кошки)"
    file_types: ".jpg, .png"
    allow_multiple: false
- type: checkbox
  id: accept-terms
  attributes:
    label: "Я прочитал и согласен с условиями"
    description: "Для продолжения необходимо принять условия"
  validations:
    required: true

Валидация

Для каждого поля можно добавить параметры валидации, которые должны быть выполнены перед созданием формы. Чтобы увидеть список доступных правил валидации, нажмите кнопку Валидация над редактором кода. Это покажет синтаксис для каждого параметра валидации и опишет его назначение.

Параметры валидации

Ключ Тип Описание
required boolean Требует заполнения поля для отправки формы
minimum integer Для текстовых полей указывает минимальное количество разрешённых символов
maximum integer Для текстовых полей указывает максимальное количество разрешённых символов
pattern regex string Для текстовых полей — регулярное выражение, определяющее допустимый ввод
type string Для полей ввода можно указать ожидаемый тип ввода (text

Применение шаблона к категории

После создания шаблона формы вы захотите применить его к категории. Для этого перейдите в настройки категории, к которой хотите применить шаблон.

Выберите меню Шаблон, а затем справа используйте переключатель для включения шаблонов форм. После включения вы сможете использовать выпадающий список, чтобы добавить один или несколько шаблонов к категории.

Заполнение формы

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

При заполнении формы будут применяться все правила валидации, указанные в определении шаблона формы. Отправить форму и создать тему можно будет только после того, как она станет валидной. Нажмите :heavy_plus_sign: Создать тему, и контент темы будет сгенерирован на основе всех заполненных полей.

Наконец, после отправки контент темы будет состоять из всех заполненных полей:

Предварительное заполнение значений формы

Вы также можете предварительно заполнить значения формы, вызвав /new-topic с параметрами, соответствующими идентификаторам полей, определённым в шаблоне формы. Например, для ранее использованного в качестве примера шаблона:

/new-topic?name=John%20Smith&favorite-animal=Cat

Дорожная карта

  • Сохранение вывода JSON в данные темы при создании темы
  • Переключатель для возможности выбора и использования свободного редактора в категориях с шаблонами форм

Как вы можете нам помочь

Мы будем рады услышать ваши отзывы об этой новой функции. Если вы администратор и хотите опробовать её на своём форуме, вы можете включить настройку experimental_form_templates и начать использовать её прямо сейчас!

Пожалуйста, создавайте новые темы с тегом form-templates, чтобы поделиться своим опытом, сообщить об ошибках или предложить улучшения.

Спасибо, что помогаете нам делать Discourse лучше!

90 лайков
Form submission plugin?
How to include the label/text on the post creation textbox?
New Topic template form, like GitHub Issue templates?
Visual form entry topic templates?
Form-fields for topic creation rather than a text box
Have users complete form when creating a topic?
Check boxes and Mandatory fields in Topic templates?
Can topic templates have javascript?
Use a form to make a topic
Anyway to make Forms in Discourse - One Category?
Topic template cannot allow user to upload media, and the 3 lines at the top do nothing
Need an event check list / sign off plugin?
How to track a weekly form on Discourse?
How would someone go about having a category only allow photo "submissions" as new topics?
Discourse forum for feature requests with upvotes + comments?
Introducing Discourse Discover
Configuring our Support category for email-only topic creation
Marketplace category template format change suggestion
Plugin for adding extra fields to the question form
Does this platform not give users templates when creating posts?
Any recommendations on an optimal configuration for managing issues using Discourse?
Are form templates still a thing?
How can I add custom fields to the composer?
Application Forms for User Groups Automation
Is it possible to change Topic Title prompt for a category?
Creating a system to move topics based on given criteria such as a timestamp
Discourse Preset Topic Composer
How can I add custom fields to the composer?
Custom Topic Fields
Pre-post question/ acknowledgement
Embed additional explainer text in Form Template
Embed additional explainer text in Form Template
How to customize composer
Custom topic fields per category or custom topic entry form per category?
Content Validation: Require At Least 2 Keywords Including Either test1 or test2 in New Topics
Structuring an active support community migrating from Facebook
Using templates when quoting
Advice on a support forum
Quiz form with explanations?
How to create a custom form in composer?
Form template for Personal messages
Are the tables on top of some posts markdown or a feature?
Building a practitioner directory or category in a community
Building a practitioner directory or category in a community
Anonymous posting for logged-in users
Balancing Costs and Functionality in AI-Powered Forums
Canned Replies without extra lines
Setting Form Templates with a tag

This looks very useful and I’ll definitely be enabling it to experiment.

One thing I’d find useful is the ability to link a template field to a user custom field. For example, in a support category the first couple of questions usually asked by the support guys are “Model of equipment” and the associated “Web site URL”. With this template feature I can now ask for this info as ech new topic is created :smiley:

These two bits of info are also generally of interest to other users so they’re defined as custom user fields - which sometimes get filled in. If template fields could be populated from a linked custom user field (if it has a value in it) then for frequent flyers they can fill in their user fields and not have to fill in the template fields in every time. Occasional flyers can just fill in the template fields as and when they need support.

As a further suggestion, the icing on the cake would be for the link to work in reverse. If someone enters data onto the template that’s not in the linked custom user field then the custom field is updated when the topic is posted.

13 лайков

Hello :wave:

This is one of the best improvement. It gives so many opportunities. :heart_eyes:

Some notes:

  1. It seems the form_templates.errors.valueMissing.number is a missing string.

  2. It seems the tel validation is not working.

  3. On mobile the form template in composer is not scrollable.

  4. On mobile when the form template is available the footer buttons doesn’t do anything. I think it would be good to hide these.
    Screenshot 2023-10-17 at 8.04.50

+ Would be useful to add validation to prevents negative numbers to number type. Use case (price) :slightly_smiling_face:

+ Would be also useful to add dynamic conditional fields feature.


Thanks :slight_smile:

15 лайков

As already mentioned, this will be very handy for support contexts and I particularly like the suggestions from @packman regarding custom user fields.

Is adding form templates to groups also on the roadmap (or could it be)? Where messaging a group is used for private support, this will be especially useful for front-loading questions before a member of staff arrives.


Depending on the visibility of the custom field, this could have privacy implications. For example, the user might choose to share the information via a form template in a private category but not want to share that information with the wider community via their profile.

Depending on the nature of the information, it might also have one value that is appropriate for their profile and/or most forms but they might want to provide a different value in a particular instance.

I like the idea of filling in the form from those fields and being able to update the fields if the entered values differ but perhaps that should be a prompt. This is a really quick and dirty mock-up but maybe something along these lines after creating the topic (only if a value differs and possibly only if non-empty):

8 лайков

My feature request for this great new feature, is, I believe, common in software support forums.

People neglect to specify their version of the software. That’s it. Simple, but it is the cause of many, many useless back-and-forth posts that are tiresome to the people who help out a lot of people (and we don’t want to tire the most important people in the Community).

So I would want a form to ask

  • Your FabulousApp version is… (dropdown with options)
  • Your PHP version is… (dropdown with options)

Now, suppose that someone posts frequently on the forums. This information does not change frequently, although it might change say, once a month.

The form should keep that values that this same user selected in their previous post, as defaults, that’s my feature request right there. What do you think?

5 лайков

I think that in some cases, having a pre-filled field may lead to users overlooking it and not changing the value when it’s needed. :thinking:

Purely speculating, though.

11 лайков

These two combined is what I would like to see for my use case. With multiple apps, I want the user to be able to select their app, then select their version from a list that corresponds to that app.

This is certainly my experience for choices. With a default value on an email contact form, the vast majority of submissions have that default value regardless of which app or version they’re actually using.

3 лайка

That’s probably true for default values but in what I envisaged the field values would be those previously entered by the user in their custom fields. These could be old/outdated but I think in my use case there would be far fewer wrong values than there are currently no values.

2 лайка

Absolutely. To my mind these are mostly two different categories of information: state at a point in time and user preference/identity/etc. What I was referring to with my experience of default values was more about the former.

2 лайка

Two requests!

  1. A code field that automatically fences the content with ```
    • It could have a language dropdown, with a default.
  2. An attribute that allows users to duplicate a field (I picture a + button below that field).
    • Imagine if a user wants to post two codeblocks, or multiple images. They can input one, click the + and add another.
16 лайков

This is a great new feature, and potentially well timed for a project I’m working on.

After playing about with it briefly I have two questions:

  1. Currently when the user edits a topic post they have created through a form template it just shows the default post editor.
    Are there plans to also show the form template editor when editing a post?

  2. Will there be an option to add custom input types?
    I’m thinking about a map where a user can select their location by dropping a pin on the map. So it would be good to have the option to define such custom field types.

5 лайков

This is perfect timing for my use case! I’m wondering if there’s plans to eventually allow customization for how a form template ends up being rendered in a topic.

e.g. In the following image the checkbox field type is rendered as the text on:

Would someone eventually be able to map the form field types to customized output?

e.g. In my case I want a checked/on checkbox to map to the checkbox formatting, [x], and the lack of a check/off state to []

I might have to start learning ruby and hacking around on this project, this form update has given me lots of neat ideas. Thanks for the great work guys!

3 лайка

This is absolute great way to enforce some behaviour in a particular category (my painpoint was job posting, where everyone posted however they feel like :smiley: )!

A bunch of features extra would be nice:

  • the ability to „switch to no template” (optional). This would be nice to be limited by users, by level, by group etc; Some kind of „trust me bro, I know what I’m doing!”
  • multiple fields on the same row (think first name + last name). A good enough fix would be to allow admins to set a class name for the form template;
  • a repeater (i.e. group a bunch of fields and let users to add more of those);
7 лайков

It would be good to have the ability to:

  • Paste content into an Upload field[1].
  • Add a composer in addition to the textarea, where users have access to the normal suite of features.[2]

  1. The upload functionality in Discourse posts is great. This one’s more difficult to use, requiring images already be saved to disk for example. ↩︎

  2. If I want a user to select a dropdown in addition to a post, with the current approach (a textarea) I dramatically decrease their ability to create their post normally; no pasting images, no edit bar, etc. ↩︎

9 лайков

I tried the form here to report a bug about the theme. Here is my feedback:

  • The form itself is a great idea :+1:
  • No formatting tool is a big miss.
    • Even if markdown syntax is basic, selecting and using the toolbar is often easier/faster. It helps in making a readable message.
    • This can work if the report is a simple but advanced issue; you might need to hide details or insert a table.
  • No inline upload is not convenient.
    • E.g., showing a problem step by step, before/after results, etc.
    • In case of multiple screenshots, you must explain what screenshots you should look at.
  • Same as Thomas, pasting an image would be welcomed. It took me some time to figure out where my screenshots were saved. :smile:
  • Conditional input – when selecting “other,” it would be nice to have an input appearing for that.

Overall, really nice! I’m looking forward to how it will be improved. :slight_smile:

9 лайков

If you have multiple forms enabled for a single category, it isn’t intuitive that there is a dropdown for you to select a form. When you create a new topic, it automatically populates the first form template, which again, if you don’t know what you’re looking at, then you wouldn’t realize there could be other forms.

When you deselect the form, you do see the text “Select form templates” which is clear to me that there is a list of form(s) that I choose from. The composer still shows the form even though one is not selected. This is where I would second, @iamntz about having the option to switch to no template.

6 лайков

Just want to add on to my previous reply and to give a bit more context to our specific use case. We’re looking to implement this in our Site Feedback category. Ideally, we want form templates for things like requesting tags, and keep the default composer (no template option), if the form does not exist or won’t do the job properly.

So, what we’re envisioning would be to create new topic in category and see this:

From there, see “Select form templates”, where from there you can either compose normally or see that form(s) do exist in this category for standardized requests/feedback. :slight_smile:

I can see the argument that some users won’t see or use the form template, if they can compose, but I was trying to stay within the current styling with the placeholder text within the field instead of a label outside of the field. But that’s why it could be an optional feature where the admins enable/disable it. :upside_down_face:

4 лайка

If the selection button was clearly highlighted it would be much easier to encourage users to click it, similar to your Create Topic button

3 лайка

After playing around with the forms more, we discovered a workaround for a “no template” option would be to create a simple “free response” form that can serve as a no template (as seen in the screenshot below).

Adding to this idea, if we didn’t want to change the color to highlight the dropdown, I think adding a down arrow would be a helpful indicator that there is a drop-down selection, just like the categories drop-down.

We discovered that the forms are ordered alphabetically. It would be amazing to have the option to reorder the forms or the option to select the default form that should appear when creating a new topic.

Needless to say, we like what this feature has to offer, and would be excited for such enhancements to it. :slight_smile:

6 лайков

Perhaps I’ve missed it, but is there any way to have a hyperlink in a form? For example, say we had a checkbox for the terms and conditions. In the description it would be useful to have a hyperlink to the actual terms and conditions.

Is this already possible?

Is there also any way to automatically populate the title field when the user creates a new post, such as with their username, or even just some default title?

8 лайков