Filter using many2many field...

Asked by Pavithra

Hi all,

 How to apply domain to a field based on the values selected in many2many field?

Question information

Language:
English Edit question
Status:
Solved
For:
Odoo Web Client Edit question
Assignee:
No assignee Edit question
Solved by:
ksh (Axelor)
Solved:
Last query:
Last reply:
Revision history for this message
Best ksh (Axelor) (ksh-axelor) said :
#1

Hello Pavithra,

       try using this domain="[('id', 'in', many2many-field[0][2])]" where many2many-field[0][2] will evaluate to the ids of selected many2many.
  Ex. domain="[('id', 'in', category_id[0][2])]" in partner.

Hope, this may solve your query.

Revision history for this message
Pavithra (pavithra-lakshmanan) said :
#2

Thanks ksh (Axelor), that solved my question.

Revision history for this message
Mohamed Fadhel Hadj Salem (med-fadhel) said :
#3

Thanks a lot

Revision history for this message
jordg (gbj) said :
#4

Here is a detailed solution for a scenario when we want to show a subset of products specifically in a BOM to make selecting the correct products easier
XML:
                     <!-- You need to initialise "bom_product_ids" but do not need to see it -->
                     <field name="bom_product_ids" nolabel="1" widget="many2many" invisible="1"/>
                     <!-- "bom_item_ids" are filtered on the output of "bom_product_ids" -->
                    <field name="bom_item_ids" nolabel="1" widget="many2many" domain="[('id', 'in', bom_product_ids[0][2])]" colspan="4"/>

Python:

    def _get_bom_product_ids(self, cr, uid, ids, name, arg, context=None):
        res = {}
        bom_obj = self.pool.get('mrp.bom')
        for r in self.browse(cr, uid, ids):
            product_ids = []
            bom = bom_obj.browse(cr, uid, bom_obj.search(cr, uid, [('routing_id', '=', r.routing_id.id)]), context=context)
            if bom:
                bom_ids = bom_obj.search(cr, uid, [('bom_id', '=', [bom[0].id])])
                for b in bom_obj.browse(cr, uid, bom_ids, context=context):
                    product_ids.append(b.product_id.id)
            res[r.id] = product_ids
        return res

_columns {
        'bom_product_ids': fields.function(_get_bom_product_ids, method=True, type='many2many', relation='product.product', string='BOM Products' ),
        'bom_item_ids': fields.many2many('product.product', 'mrp_routing_workcenter_product_rel', 'routing_workcenter_id', 'product_id', 'Linked BOM Items', help="These are products that require to be consumed before this WO can procede"),
}

Many thanks for this post

Revision history for this message
Bernard K Too (bernard-kipkorir-too) said :
#5

If you want to avoid javascript errors when the Many2many is empty, you can refine the domain attribute as follows:

domain="[('id', 'in', (bom_product_ids and bom_product_ids[0][2] or False ))]"