HOWTO: Create a custom field, save and retrieve data from it (WIP)

This is really incomplete and is a first pass at noting down the process of creating a custom field and making it save to the DB, and be retrieved into the JSON for display and use in the frontend. As much as anything it’s an aide-memoire for me. I’ll wikify the post and I’m happy for others to edit and add.

stuff you need to do in plugin.rb (or in code you are going to require in plugin.rb)

In this case I have been working on Topic custom fields, so the example uses Topic custom fields

# plugin.rb

after_initialize do

  # Register Topic custom field for a Thing, stating its data type
  Topic.register_custom_field_type('thing', :boolean)

  # Add to the serializer so that the data is pulled out of Rails into the .json 
  add_to_serializer :topic_view, :is_thing do

  # whitelist the parameter so that it can be saved in the controller

  # using Discourse 'Topic Created' event to trigger a save.
  # `opts[]` is how you pass the data back from the frontend into Rails
  on(:topic_created) do |topic, opts, user|
    if opts[:thing] != nil
      topic.custom_fields['thing'] = opts[:thing]


Sources of help

Other Pavilion Plugins

This searches Pavilion’s GitHub repos for add_to_serializer instances:

Discourse Meta

Pavilion’s Mattermost chat

Pavilion Members

Loads missing but will leave for now