Search code examples
filterodooodoo-9

How to filter a domain view with a function? In odoo 9


I want to filter a domain with a function instead of a variable in order to show only some registers in the view. I have done this:

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

    @api.multi
    def custom_funct_date(self):
        my_date = ... (some stuff)
        return my_date

Then, in the view, I have filtered the domain:

<?xml version="1.0"?>
<openerp>
  <data>
    <record id='action_menu_custom_date' model='ir.actions.act_window'>
      <field name="name">This is a test</field>
      <field name="res_model">sale.order</field>
      <field name="view_type">form</field>
      <field name="view_mode">tree,form</field>
      <field name="domain">[('date_order','>=',custom_funct_date)]</field>
    </record>
  </data>
</openerp>

But this is giving me an error:

ValueError: "name 'custom_funct_date' is not defined" while evaluating
u"[('date_order','>=',custom_funct_date)]" 

Solution

  • instead of using ir.actions.act_window use ir.actions.server using server action you can call your function and return a action to open your model using your computed domain.

        <record id="action_menu_custom_dat" model="ir.actions.server">
            <field name="name">Your Action</field>
            <field name="model_id" ref="sale.model_sale_order"/>
            <field name="state">code</field>
            <field name="code">action = self.custom_funct_date(cr, uid, context=context)</field>
            <field eval="True" name="condition"/>
        </record>
    

    and in your model change the method to:

         def custom_funct_date(self, cr, uid, context=None):
                # print "make sure that this action is called from th server action "
                # compute you date
                my_date = ... (some stuff)
                tree_id = self.env.ref("modul_name.view_tree_id")
                form_id = self.env.ref("modul_name.view_form_id")
                return {
                    'type': 'ir.actions.act_window',
                    'name': 'This is a test',
                    'view_type': 'form',
                    'view_mode': 'tree,form',
                    'res_model': 'sale.order',
                    'domain': [('date_order','>=',my_date)],
                    # if you don't want to specify form for example
                    # (False, 'form') just pass False 
                    'views': [(tree_id.id, 'tree'), (form_id.id, 'form')],
                    'target': 'current',
                    'context': context,
                }