如何在Odoo 10中获取JavaScript中的当前记录?

How to get the current record in JavaScript in Odoo 10?

有谁知道如何在从 JavaScript 代码调用的 Python 方法中获取当前记录?

举个例子:

我有我的Python方法:

@api.multi
def my_method(self):
    _logger.info(self)

要从我的 JS 代码调用该方法,我必须执行以下操作:

var MyModel = new Model('my.model');
MyModel.call(
    'my_method', [current_id],
)

因此,我需要从 JavaScript 获取当前 ID。所以,在调用该方法之前,我将当前 ID 存储在一个 JS 变量中:

var current_id = this.field_manager.datarecord.id

它工作正常。但只有当记录已经有一个 ID 时。如果当前正在创建当前记录,this.field_manager.datarecord.idreturnsnull,方法调用失败

我想知道如何调用该方法,即使记录还没有 ID。例如,onchange 装饰器允许您在 Python 中处理未存储在数据库中因此还没有 ID 的记录。

有什么想法吗?

我不知道这是否对你有帮助,但你不能 在 api.multi 中调用方法而不先保存 但您可以使用 api.model 代替 并在函数调用中传递记录的 id 在参数中。

MyModel.call(
'my_method', {'current_rec': current_id})

在你python处理创建模式

  @api.model
  def my_method(self, current_rec=None):
       if not current_rec:
            # in create mode
            # if you need a field from the view you need to pass its value in params like the id
            # because self is a dummy record that is empty not like in onchange event
            # because odoo build that dummy record for you from the values that they
            # are in the current view.
       else:
            rec = self.browser(current_rec)
            # remember value in api.multi or in rec are retrieved from the database
            # not the current view values so if you relay on a value from the view 
            # pass it in params or find a way to tell odoo to build a dummy record like in onchange.

       return result

这里的问题self是空的(在创建模式下)不像 在 onchange 方法中。

但是你总是可以传递额外的参数,你可以从当前视图中获取这些参数并将它们传递给方法 如果您的逻辑需要它们。

不要忘记,如果您在逻辑中使用字段,在 api.multi 中您使用的是值 从数据库中检索的不是它们在当前视图(在编辑模式下)中的值。