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); }); } |
test
1 2 3 4 5 6 7 | async hello() { await this.rpc.query({ model: "account.move" , method: "justtest" , args: [( "id" , "=" , 1 )], }); } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示