Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Raise a validation error if a field is empty odoo 12?

Tags:

odoo

What I have tried to do is that if the specialist_name is empty, I have to raise a Validation Error. But it is not working. What am I doing wrong? My python code is below:

specialist_name = fields.Many2one(
    'res.partner',domain=[('is_specialist','=',True)],string="Specialist")

@api.constrains('specialist_name')
def _onchange_value(self):
    if self.specialist_name == False:
        raise ValidationError(_('Only The Specialist Has The Provision To Create'))

like image 561
Raihan Avatar asked Jan 29 '26 09:01

Raihan


2 Answers

specialist_name is a Many2one field, and the value of such a field is a recordset of size 0 (no record) or 1 (a single record).

The self.specialist_name == False expression will be always evaluated to False and the body of if statement will never be executed.

Empty records are evaluated to False in a boolean context such as if or while statements, try to use:

if not self.specialist_name:

Edit:

@constrains will be triggered only if the declared fields in the decorated method are included in the create or write call. It implies that fields not present in a view will not trigger a call during record creation. An override of create is necessary to make sure a constraint will always be triggered (e.g. to test the absence of value).

If you override the create or write method, you will find that specialist_name key is not present in values and if you add the specialist name to values the constraint will work.

When we set a read-only field, we prevent the user from modifying it and handle its value in the background. We do not need to warn the user since the value of the field can't be changed from the UI.

like image 81
Kenly Avatar answered Jan 31 '26 22:01

Kenly


Why not using a more simpler solution and making the field required?

There are broadly speaking two positions/areas to do it.

  1. on views, which will give you some flexibility on implemented processes (maybe there will be cases where you don't want to have it required)
<field name="my_field" required="1" />
  1. on field declaration
my_field = fields.Many2one(comodel_name="my.comodel", required=True)
like image 35
CZoellner Avatar answered Jan 31 '26 21:01

CZoellner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!