实践环境

Odoo 14.0-20221212 (Community Edition)

代码实现

在js脚本函数中调用模型中自定义方法:

this._rpc({
    model: 'demo.wizard', // 模型名称,即模型类定义中 _name 的值
    method: 'action_select_records_via_checkbox', // 模型中自定义名称
    args: ['arg_value'] // 传递给模型方法参数列表,列表中每个元素对应模型方法的一个位置参数
}).then(function (res) { // res为模型方法返回值
    console.log(res);
    // do something
});

模型方法定义

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from odoo import models,fields,api
class DemoWizard(models.TransientModel):
    _name = 'demo.wizard'
    _description = 'demo wizard'
    #...此处代码已省略
    @api.model
    def action_select_records_via_checkbox(self, *args):
        '''通过wizard窗口界面复选框选取记录时触发的操作
        @params: args 为tuple元组,如果方法不采用位置参数,则传递的是啥,参数就是啥
        '''
        # do something
        return True

注意:this._rpc函数不能在非普通函数中使用,其使用范围可参考以下示例

odoo.define('estate.ListRenderer', function (require) {
    "use strict";
 	var ListRenderer = require('web.ListRenderer');
	ListRenderer = ListRenderer.extend({
        _onToggleCheckbox: function (ev) {
            //// ...此处代码已省略
            this._rpc({
                model: this.modelName,
                method: this.modelMethod,
                args: [this.recordsSelected]
            }).then(function (res) {
                // ...此处代码已省略
            });
             ...
            this._super.apply(this, arguments);
        }
	});
    // ...此处代码已省略
});

那问题来了,如果希望在普通的javascript函数中使用上述请求功能,咋办?参考如下示例代码

示例代码

function do_confirm_action(modelName, modelMethod){
    $("button[name='action_confirm']").attr("disabled", true);
    var wizard_dialog = $(event.currentTarget.offsetParent.parentElement.parentElement);
    var dataUUID = $(event.currentTarget.parentElement.parentElement.parentElement.parentElement).find('div.o_list_view').prop('id');
    var rpc = odoo.__DEBUG__.services['web.rpc']; 
    rpc.query({
        model: modelName,
        method: modelMethod,
        args: [JSON.parse(window.sessionStorage.getItem(dataUUID) || '{}')]
    }).then(function (res) {
        if (res == true) {
            wizard_dialog.css('display', 'none');
            window.sessionStorage.removeItem(dataUUID);
        } else {
            $("button[name='action_confirm']").attr("disabled", false);
        }
    }).catch(function (err) {
        $("button[name='action_confirm']").attr("disabled", false);
    });
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。