Nahid Jawad Angon
Nahid Jawad Angon

Reputation: 5

How to raise an error odoo while selecting multiple items in odoo

How can I raise an error while the user selects multiple items from many2many fields? The user can select only one item if he selects multiple items then I want to raise an error.

user_ids = fields.Many2many('res.users', string="Salesperson", required=False)

Upvotes: 0

Views: 172

Answers (1)

icra
icra

Reputation: 501

There is no way to detect server sidely how many records are selected in your Many2many field, this requires a client-side approach (injecting some javascripts)

However, you could validate your field content length before saving parent record.

from odoo.exceptions import ValidationError

user_ids = fields.Many2many('res.users', string="Salesperson", required=False)

def write(self, values):
  res = super(MyModel, self).write(values)

  for record in self:
    if len(record.user_ids) > 1:
      raise ValidationError("No multiple items allowed")
  
  return res

If you always intend to have only a single relation, consider using Many2one instead.

user_id = fields.Many2one(comodel_name='res.users', string="Salesperson", required=False)

Upvotes: 1

Related Questions