Reynaldi Yosfino
Reynaldi Yosfino

Reputation: 78

Odoo - Give a warning when editing some field with empty value

I want to add an entry to the suppliers table if one creates a new or edits a product. Each product must have a supplier. If a supplier is not selected, system must give a warning “You should fill in the supplier details, at least one.”

Here is my code:

class warning_supplier(models.Model):
_inherit = 'product.template'

@api.multi
def write(self, vals):
    res = super(warning_supplier, self).write(vals)
    supplier_id = self.env['res.partner'].search([('name','=','No Supplier')])
    for this in self:
        seller_ids = this.seller_ids
        if len(seller_ids)==0:
            raise Warning('You should fill in the supplier details, at least one.')
    return res

When I create products, the code runs correctly.

But when I edit a product & remove the selected supplier, it does not work any more.

Can someone pinpoint the error to me? Thanks!


Edit: Fixed by using constraints.

Upvotes: 2

Views: 1733

Answers (2)

You can add python constraint, that will execute when given field has been modified.

class product_template(models.Model):
    _inherit = 'product.template'

    @api.multi
    @api.constrains('seller_ids')
    def onchange_seller(self):
        for record in self :
            if not record.seller_ids :
                raise ValidationError("You should fill in the supplier details, at least one.")
        return

For more information about constrains : click here

Upvotes: 2

Dachi Darchiashvili
Dachi Darchiashvili

Reputation: 769

When you are creating product create function is called, and on edit always write function.

In create you should check vals parameter and if it doesn't meet the requirements you should warn user to correct it and after that edit actual record.

Try something like this

# For example boolean
if vals["myBoolean"] == False:
    raise Warning('myBoolean should be true always!')

Upvotes: 0

Related Questions