简体   繁体   中英

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

Does anyone know how to obtain the current record in a Python method which is called from JavaScript code?

Let's put an example:

I have my Python method:

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

To call that method from my JS code, I have to do the following:

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

And because of this I need to get the current ID from JavaScript. So, before calling the method, I store the current ID in a JS variable this way:

var current_id = this.field_manager.datarecord.id

It works OK. But only when the record has already an ID. If the current record is currently being created, this.field_manager.datarecord.id returns null , and the method call fails.

What I would like is to know how to call that method even when the record has not an ID yet. For example, onchange decorator allows you to work in Python with records with are not stored in the database and therefore have not an ID yet.

Any ideas?

I don't know if this will help you but you can not call a mehtod in api.multi withou being saved first but you can work arround it use api.model instead and in the funcition call just pass the id of the record in the parametre.

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

In you python handle the create mode

  @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

The problem here self is empty (in create mode) not like in onchange method.

but you can always pass extra params that you can get from the current view and pass them to the method If they are needed in your logic.

And don't forget if you are using a field in your logic, in api.multi you are using values retrieved from the database not the values that they are in the current view (in edit mode).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM