Odoo 通过Javascript调用模型中自定义方法

实践环境

Odoo 14.0-20221212 (Community Edition)

代码实现

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

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

  

模型方法定义

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/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函数不能在非普通函数中使用,其使用范围可参考以下示例

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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函数中使用上述请求功能,咋办?参考如下示例代码

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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);
    });
 
}

  

 

posted @   CrossPython  阅读(74)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示