Odoo14自定义one2many控件新增按钮触发保存报TypeError如何解决
问题根因
你的实现方式存在两处核心问题:
- Odoo14原生
_onAddRecord方法仅负责初始化新增行的编辑状态,本身没有返回Promise对象,上层逻辑尝试调用返回值的.then()方法就会抛出Cannot read property 'then' of undefined错误 - 原生方法默认不会触发即时保存,仅会把新增数据暂存在前端缓存,还是需要点击全局保存才会同步到数据库
可行实现方案
按照以下步骤修改即可实现点击自定义按钮新增并自动保存的需求:
1. 替换事件处理函数逻辑
不要直接调用原生_onAddRecord,自行实现新增+自动保存的完整逻辑:
_onAddIconClick: async function(event) { event.stopPropagation(); // 1. 调用模型方法新增行,at:0对应你配置的editable="top",新增在列表顶部 const newRecord = this.model.addNewLine({ at: 0, editable: true }); // 2. 等待行编辑界面渲染完成 await this._render(); // 3. 主动触发保存逻辑,返回Promise适配上层调用规则 return this.saveRecord(newRecord.id) .then(() => { // 保存成功后触发父视图更新,同步one2many关联状态 this.trigger_up('field_changed', { dataPointID: this.dataPointID, changes: {}, viewType: 'list' }); }) .catch(err => { // 校验失败时回滚新增行,避免残留脏数据 this.model.removeLine(newRecord.id); return this._render(); }); }
2. 修正事件绑定规则
给你的自定义按钮添加专属类名custom_list_add_btn,避免和Odoo原生新增按钮的事件冲突,事件绑定修改为:
'click tr .custom_list_add_btn': '_onAddIconClick',
3. XML配置优化(可选)
如果要隐藏原生的全局新增按钮,只保留你的自定义按钮,可以在tree的options配置里关闭原生新增开关:
<field name="attribute_line_ids" widget="table_one2many" context="{'show_attribute': False}" attrs="{'invisible':[('has_variants','=', False)]}" > <tree string="Variants" editable="top" multi_edit="1" options="{'only_one_row': 'True', 'add_record': false}" > <field name="attribute_id" attrs="{'readonly': [('id', '!=', False)]}" string="Opción"/> <field name="value_ids" string="Valores (Sepáralos con un tab)" widget="many2many_tags_variaciones_bb" options="{'no_create_edit': False}" context="{'default_attribute_id': attribute_id, 'show_attribute': False}"/> </tree> </field>
内容的提问来源于stack exchange,提问作者Maicoly Morocho
相关产品推荐
相关产品推荐

