This question has been flagged
3 Replies
12399 Views

I have created a new module in Odoo v8 and created one template in it. For that template based on some values I need to call a python method from a JS file. I have tried the following methods:

1)

function openerp_pos_models(instance){

var myModel = new instance.web.Model('my.model');

});

but on loading the page it shows instance is not defined?

2) var Users = new openerp.web.Model('res.users');

this one shows Uncaught ReferenceError: openerp is not defined and Uncaught TypeError: Cannot read property 'Model' of undefined.


How can call a method from a JS file in odoo v8? The above methods are working in v7 and v8 base modules.

Avatar
Discard

me too want to know.. this.

You should make Ajax /jQuery calls from the Javascript to the Python method. Have a look at http://stackoverflow.com/questions/13175510/call-python-function-from-javascript-code this for example. Should be working in Odoo too.

Best Answer

Hi,

You need to define the instance for your custom module like this:

Here, "custom_module" is the folder name of your module. And here I have just created a widget. And you can call a python method using the call() function as shown in example. Just mention the name of method(eg: "action_test"), which is defined in your model. After method name, the second arguement is used pass some context if any.


For example:

in .py file


class custom_module(models.Model):

_inherit = "product.product"

@api.model

def my_method(self):

      return {"hello": "world"}


in .js file

openerp.custom_module = function(instance, local) {

      var _t = instance.web._t,

      _lt = instance.web._lt;

      var QWeb = instance.web.qweb;

      local.WidgetName = instance.Widget.extend({

 

              start: function () {

               this.$el.append(QWeb.render("YourTemplateName",{name: "Your name"})); // this is another way of selecting template and pass values in context to that template

              

                    var self = this;

                    var model = new instance.web.Model("product.product");

                    model.call("my_method", {context: new instance.web.CompoundContext()}).then(function(result) {

                    self.$el.append("<div>Hello " + result["hello"] + "</div>");

                                   });

          }

});

instance.web.client_actions.add('your.object', 'instance.custom_module.WidgetName');

Avatar
Discard
Author

It shows the following error: ""Uncaught TypeError: Cannot read property 'web' of undefined "" from the following line: return new instance.web.Model('product.product')