How does the 'Add user to group through User Custom Field' script work?

AI-generated summary

The Add user to group through User Custom Field script by leonardo adds users to groups based on their selection in a custom field. The script, intended for specific use cases, runs on a recurring trigger and works with Dropdown type user fields that contain a list of choices. If a user selects a value and a group with that exact full name exists, the user will be added to the group.

leonardo clarified that the script does not support Multiselect user fields, as it only allows for a single target group. However, they welcome Pull Requests (PRs) to add this functionality. It’s also recommended to avoid using the script with text user fields, as it would allow users to choose any group to be added to.

How does the Add user to group through User Custom Field (by @leonardo) script work?

I can’t get it to work despite trying a few things and trying to decipher the code. But it would be really helpful!

Hi Nathan!

It’s meant for a rather specific use case where you want to ensure that users belong to a certain group based on a custom field that they filled in on signup.

Let’s say the custom field is “favorite soccer team” and it contains a list of choices. The script runs on a recurring trigger, so users will eventually end up belonging to a group with the same full name (not just name) as the value they chose, if the group exists.

You can look at the tests for some synthetic examples: https://github.com/discourse/discourse-automation/blob/main/spec/scripts/add_user_to_group_through_custom_field_spec.rb

Brilliant! Would that also work for Multiselect user fields? It could be just what I’m looking for.

It will only make sense with Dropdown type user fields, because Multiselects allow choosing more than one value and the script does not support multiple groups as target. It’s doable, but it would complicate the logic a bit. PRs welcome :slight_smile:

Caveat: never use this with a text user field, because users would then be able to choose any group to be added to. So far Dropdown is the only sane choice.