我正在尝试了解如何为话题添加自定义字段,并正在通过一个非常基础的示例进行实践。目标:为每个创建的话题添加一个名为 “sample_field” 的自定义字段,其值为一个简单的字符串。
我已经查阅了各种示例,例如 poll 插件、solved 插件 以及 这篇讨论,但这些插件对自定义字段的操作过于复杂,我尚未理清所需的基础代码。
所以我还没完全搞定——我的 plugin.rb 文件似乎缺少某些内容(我认为),而且我还没弄清楚如何在话题创建时将字符串值绑定到自定义字段上。
我需要做什么才能让这生效?
任何帮助都将不胜感激。谢谢!
以下是我目前的代码:
plugin.rb:
// 创建自定义字段:
after_initialize do
Topic.register_custom_field_type('sample_field', :string)
add_to_serializer(:topic_view, :custom_fields) { object.custom_fields } // 如果我想在客户端显示自定义字段
end
assets/javascripts/initializers/topic-custom-field.js.es6:
// 初始化自定义字段对象,并使其能够发送到服务器:
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
});
}
})
})
}
}
那么,如何在话题保存时为自定义字段添加值呢?
我认为话题的“保存”关键操作在代码库中发生在这里:
app/templates/composer.hbs:
<div class="save-or-cancel">
{{#unless model.viewFullscreen}}
{{composer-save-button action=(action "save")
icon=saveIcon
label=saveLabel
disableSubmit=disableSubmit}}
...
当该“保存”操作发生时,我该如何执行某些操作(在本例中,为自定义字段添加一个值)?
我尝试在 initializers 下创建一个 js 文件,在其中我可以执行类似以下的操作:
api.modifyClass('component:composer-save-button', {
actions: {
topic.set('custom_fields.sample_field', 'here's a value for the sample_field')
}
}
但我需要将那个 “topic.set” 与 composer.hbs 中的 “save” 操作关联起来,而我不知道该如何实现。
如果有更简单的方法,我也很乐意听取建议!