I’m trying to understand how to add a custom field to topics, and working through a very basic example. Goal: Add a custom field called “sample_field” to each topic created, with a simple string value.
I’ve reviewed various examples, like the poll plugin and the solved plugin and this discussion, but these plugins do so much more with their custom fields that I haven’t yet figured out the basic code you need.
So I’m not quite there–my plugin.rb file is missing something (I think), and I haven’t yet figured out how to bind the string value to the custom_field at the time the topic is created.
What do I need to make this work?
Any help is appreciated. Thanks!
Here’s what I’ve got
plugin.rb:
//create the custom field:
after_initialize do
Topic.register_custom_field_type('sample_field', :string)
add_to_serializer(:topic_view, :custom_fields) { object.custom_fields } //if I want to show the custom field on the client side
end
assets/javascripts/initializers/topic-custom-field.js.es6:
//initialize the custom fields object, and make it so it can be sent to the server:
import { withPluginApi } from 'discourse/lib/plugin-api';
export default {
name: 'topic-custom-field',
initialize() {
withPluginApi('0.8.31', api => {
api.modifyClass('model:topic', {
custom_fields: {},
asJSON() {
return Object.assign(this._super(), {
custom_fields: this.custom_fields
});
}
})
})
}
}
Then, how do I add the value of the custom field to the topic at the time it is saved?
I believe the key “save” action for a topic happens here in the codebase:
app/templates/composer.hbs:
<div class="save-or-cancel">
{{#unless model.viewFullscreen}}
{{composer-save-button action=(action "save")
icon=saveIcon
label=saveLabel
disableSubmit=disableSubmit}}
...
How do I do something (in this case, add a value to the custom field) when that “save” action occurs?
I’ve tried creating a js file under initializers, where I could do something like:
api.modifyClass('component:composer-save-button', {
actions: {
topic.set('custom_fields.sample_field', 'here's a value for the sample_field')
}
}
But I need to be able to link that “topic.set” to the “save” action in composer.hbs, and I don’t know how to do that.
And if there’s a simpler way to do this, I’m happy to hear it!