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
    object.topic.custom_fields['thing']
  end

  # whitelist the parameter so that it can be saved in the controller
  add_permitted_post_create_param(:story)

  # 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]
      topic.save_custom_fields(true)
    end
  end

end

Sources of help

Other Pavilion Plugins

This searches Pavilion’s GitHub repos for add_to_serializer instances:
https://github.com/search?q=org%3Apaviliondev+add_to_serializer&type=Code

Discourse Meta

Pavilion’s Mattermost chat

Pavilion Members

Loads missing but will leave for now