Search code examples
odoo

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


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'))


Solution

  • 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.