Grafana业务表单如何将自定义选项选择框重置为默认‘Choose’
问题背景
我部署了Grafana服务器,使用Business Forms制作了供他人向数据库添加数据的操作界面,表单包含以下元素:
serial : Serial Number : Text input type: Type of Item : Select with custom options (from database) pass: Pass or Fail : Radio Group with custom options (Pass, Fail)
核心需求
表单在打开时、执行重置操作后、提交完成后,必须稳定恢复至以下初始状态:
Serial Number: "" Type of Item: "Choose" Pass or Fail: [] Pass Fail
当前问题
现有自定义重置代码虽能部分清除内容,但效果不稳定,相关代码如下:
INITIAL 阶段代码
console.log(context.panel.data, context.panel.response, context.panel.initial, context.panel.elements); context.panel.setInitial({}) return; // code below is unreachable and for debugging purposes // context.panel.onOptionsChange({}) context.panel.setFormValue({ serial: "", type: 0, pass: 0, }) //const dataQuery = context.utils.toDataQueryResponse(context.panel.response); //console.log(dataQuery);
UPDATE 阶段代码
if (context.panel.response) { context.grafana.notifySuccess(['Update', 'Values updated successfully.']); context.panel.initialRequest(); context.panel.onOptionsChange({ ...context.panel.options, elements: context.panel.options.elements.map((element) => { return element.id === "name" ? { ...element, value: "test" } : element; }), }); context.grafana.refresh(); } else { context.grafana.notifyError(['Update', 'An error occurred updating values.']); }
RESET 阶段代码
context.panel.onOptionsChange({ ...context.panel.options, elements: context.panel.options.elements.map((element) => { return element.id === "name" ? { ...element, value: "test" } : element; }), });
稳定解决方案
通过封装通用重置函数,精准控制每个表单元素的初始值,结合Business Forms的API确保状态同步,彻底解决不稳定问题。
1. 封装通用重置函数
先写一个可复用的重置逻辑,统一处理所有表单元素:
function resetForm(context) { // 遍历并重置每个表单元素 const updatedElements = context.panel.options.elements.map(element => { switch(element.id) { case 'serial': // 清空文本输入框 return { ...element, value: "" }; case 'type': // 下拉框设为"Choose"(需与你配置的Select选项值完全匹配,若为索引则用对应数字) return { ...element, value: "Choose" }; case 'pass': // 清空单选组选中状态 return { ...element, value: [] }; default: return element; } }); // 更新表单配置 context.panel.onOptionsChange({ ...context.panel.options, elements: updatedElements }); // 同步表单内部状态 context.panel.setFormValue({ serial: "", type: "Choose", // 与Select的"Choose"选项值保持一致 pass: [] }); }
2. 替换各阶段代码
INITIAL 阶段
初始化时直接调用重置函数:
resetForm(context);
UPDATE 阶段
提交成功后调用重置函数,移除不必要的全局刷新:
if (context.panel.response) { context.grafana.notifySuccess(['Update', 'Values updated successfully.']); // 提交完成后重置表单 resetForm(context); // 若需要重新拉取Select的数据库选项,再解开下面的注释 // context.panel.initialRequest(); } else { context.grafana.notifyError(['Update', 'An error occurred updating values.']); }
RESET 阶段
重置按钮触发时直接调用函数:
resetForm(context);
关键注意事项
- 确认
type元素的"Choose"值与你配置的Select选项完全匹配,若选项是数字索引则替换为对应数字。 - 单选组
pass用[]即可清空选中状态,符合需求要求。 - 避免滥用
context.grafana.refresh(),仅在需要重新拉取下拉选项时使用initialRequest(),减少不必要的状态波动。
内容的提问来源于stack exchange,提问作者onering20
相关产品推荐
相关产品推荐

