跳至内容

odoo 通过 JS 调用 RPC

odoo 通过 JS 调用 RPC

Remote Procedure Call (RPC)

在 Odoo 中,远程过程调用(RPC)是一种非常重要的机制,它允许在 JavaScript 代码中调用 Odoo 后端模型的方法。下面我们来详细介绍如何在 Odoo 里通过 JS 调用 RPC。

Call method

下面是一个用于在绑定的 OpenERP 模型上调用方法的函数 `call`,它会通过 RPC 来执行相应的操作。

/**
 * Call a method (over RPC) on the bound OpenERP model.
 *
 * @param {String} method name of the method to call
 * @param {Array} [args] positional arguments
 * @param {Object} [kwargs] keyword arguments
 * @param {Object} [options] additional options for the rpc() method
 * @returns {jQuery.Deferred<>} call result
 */
call: function (method, args, kwargs, options) {
    args = args || [];
    kwargs = kwargs || {};
    if (!_.isArray(args)) {
        // call(method, kwargs)
        kwargs = args;
        args = [];
    }
    var call_kw = '/web/dataset/call_kw/' + this.name + '/' + method;
    return session.rpc(call_kw, {
        model: this.name,
        method: method,
        args: args,
        kwargs: kwargs
    }, options);
}
    

 代码解释:

  • 参数处理:函数接收四个参数,分别是要调用的方法名 `method`、位置参数 `args`、关键字参数 `kwargs` 以及额外的选项 `options`。如果没有传入 `args` 和 `kwargs`,则会将它们初始化为空数组和空对象。当 `args` 不是数组时,会将其当作 `kwargs` 处理,并将 `args` 置为空数组。
  • 构建请求 URL:通过 `this.name` 和 `method` 构建出 RPC 调用的 URL `call_kw`。
  • 发起 RPC 请求:使用 `session.rpc` 方法发起请求,将模型名、方法名、位置参数和关键字参数作为请求数据发送。

How to call wizard method from js

接下来,我们看看如何在 JavaScript 中调用向导(wizard)方法。下面是一个示例代码:

var compose_model = new Model('mail.compose.message');
return compose_model.call('create', [msg, {default_parent_id: options.parent_id}])
    .then(function(id){
        return compose_model.call('send_mail_action', [id, {}]);
    });
    

代码解释:

  • 创建模型实例:使用 `new Model('mail.compose.message')` 创建一个 `mail.compose.message` 模型的实例 `compose_model`。
  • 调用 `create` 方法:通过 `compose_model.call` 调用 `create` 方法,传入 `msg` 和包含 `default_parent_id` 的对象作为参数。该方法返回一个 `jQuery.Deferred` 对象。
  • 链式调用 `send_mail_action` 方法:当 `create` 方法调用成功后,会执行 `then` 方法中的回调函数,在回调函数中调用 `send_mail_action` 方法,并传入 `id` 作为参数。

通过这种方式,我们可以在 JavaScript 中方便地调用 Odoo 后端模型的方法,实现复杂的业务逻辑。

odoo 通过 JS 调用 RPC
中国 Odoo, 苏州远鼎 2017年8月4日
标签
存档