Search code examples
odooodoo-9qweb

How to create a button in the tree view header (next to create and import buttons) and give it functionality? In odoo 9


I am trying to add a button in the tree view of sale order module, next to create and import buttons. That button will execute a python method.

I have created my custom module, extending sale order module and then, I have followed these steps:

Step 1: Create the button in my_module/static/src/xml/qweb.xml:

<?xml version="1.0" encoding="UTF-8"?>
<templates id="template" xml:space="preserve">
  <t t-extend="ListView.buttons">
    <t t-jquery="button.o_list_button_add" t-operation="after">
      <t t-if="widget.model=='sale.order'">
        <button class="btn btn-sm btn-primary update_sales_button" type="button">Run my stuff</button>
      </t>
    </t>
  </t>
</templates>

Step 2: Add the file to the qweb section in __openerp.py__ of my module:

'depends': ['sale'],
'data': [],
'qweb': ['static/src/xml/qweb.xml'],

Now, the button appears.

Step 3: Create the python method to give functionality to the button in my_module/my_python_file.py:

from openerp import api, fields, models, _

class SaleOrderExtended(models.Model):
  _inherit = ['sale.order']

  @api.multi
  def update_sales_button(self):
    ...

Note: The python method has been tested outside of odoo and works fine.

How can I link this python method with the button?


Solution

  • You need to extend the 'ListView' widget adding a click listener. Also add the '@api.model' decorator to your method, so you can call it from js with the 'call' method. Something like this:

    ListView = require('web.ListView')
    
    ListView.include({
        render_buttons: function() {
    
            // GET BUTTON REFERENCE
            this._super.apply(this, arguments)
            if (this.$buttons) {
                var btn = this.$buttons.find('.update_sales_button')
            }
    
            // PERFORM THE ACTION
            btn.on('click', this.proxy('do_new_button'))
    
        },
        do_new_button: function() {
    
            instance.web.Model('sale.order')
                .call('update_sale_button', [[]])
                .done(function(result) {
                    < do your stuff, if you don't need to do anything remove the 'done' function >
                })
    })