Odoo 17 Development Book- Extending create() and write()

Extending create() and write()

To include any additional functionality while creating a record of the model, we can extend a model's create() function.

As an example, let's add a "notes" field to the "sale.order.".

In this instance, users who are not members of the "Administration/Access Rights" group will see a "UserError" while attempting to update the notes field.

class SaleOrder(models.Model):
    _inherit ='sale.order'
    notes = fields.Text(string='Notes')

    def create(self,vals):
        res = super(SaleOrder,self).create(vals)
        if 'notes' in vals and not self.env.user.has_group('base.group_erp_manager'):
            raise UserError(_("You cannot edit the field 'notes'"))
        return res

We can accomplish the same thing as an illustration of the write() function. We check the field's group and occurrence in the vals to write before writing, and if something goes wrong, we raise a UserError exception.

def write(self, vals):
    res = super(SaleOrder, self).write(vals)
    if 'notes' in vals and not self.env.user.has_group(
           'base.group_erp_manager'):
        raise UserError(_("You cannot edit the field 'notes'"))
    return res
whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message