Enable Dark Mode!
how-to-override-create-write-and-unlink-methods-in-odoo-17.jpg
By: Vishnuraj P

How to Override Create, Write, & Unlink Methods in Odoo 17

Technical Odoo 17

Odoo, a versatile open-source ERP platform, provides developers with the capability to finely control the creation, updating, and deletion of records through the "create," "write," and "unlink" methods. In this blog, we will unravel the significance of overriding these methods in Odoo 17, exploring how this customization empowers developers to shape the data lifecycle according to unique business needs.
The "create," "write," and "unlink" methods represent key stages in the lifecycle of records within the database:
* Create Method: Invoked when a new record is being added to a model.
* Write Method: Triggered when an existing record is being modified or updated.
* Unlink Method: Executed when a record is being deleted or unlinked from its parent model.

Overriding Create Method:

As mentioned before, the Create() method is invoked when a new record is created for the specific model. For example, here, making the “mobile” field mandatory by overriding the create method of res.partner model.
class ResPartner(models.Model):
   _inherit = "res.partner"
   @api.model
   def create(self, values):
       # Check if 'mobile' field is provided in the values
       if 'mobile' not in values or not values.get('mobile'):
           raise exceptions.ValidationError("Mobile is a mandatory field. "
                                            "Please provide a mobile number.")
       # Call the original create method to create the res.partner
       partner = super(ResPartner, self).create(values)
       return partner
The breakdown of this code is
* class ResPartner(models.Model):
   _inherit = "res.partner"
- Indicates that this model (ResPartner) is inheriting from the standard Odoo res.partner model. “_inherit” model constraint is used for inheriting a model from its parent model.
* @api.model
    def create(self, values):
- Decorates the create method, indicating that it's an Odoo API model method. The create method is called when a new record is created for the res.partner model.
* if 'mobile' not in values or not values.get('mobile'):
           raise exceptions.ValidationError("Mobile is a mandatory field. "
                                            "Please provide a mobile number.")
- Checks whether the 'mobile' field is provided in the values and if it's not empty. If not, it raises a validation error.
* partner = super(ResPartner, self).create(values)
       return partner
- Calls the original create method of the parent class (res.partner). This ensures that the standard behavior of creating a partner is preserved while enforcing the custom validation.

Overriding Write Method:

As mentioned before, the “write” method is invoked when an existing record is updated. In the previous case, we override the create method and enforce the mobile field as mandatory. So we can't create a new record without a mobile field but still we can update an existing record without adding the mobile field. To restrict this we should override the write method, for example.
@api.multi
def write(self, values):
   # Check if 'mobile' field is provided in the values
   if 'mobile' in values and not values['mobile']:
       raise exceptions.ValidationError("Mobile is a mandatory field. "
                                        "Please provide a mobile number.")
   # Call the original write method to update the res.partner record
   result = super(ResPartner, self).write(values)
   return result
Explanation of code.
* @api.multi
def write(self, values):
- Decorates the write method, indicating that it's an Odoo API multi-record method. The write method is called when updating records for the res.partner model.
* if 'mobile' in values and not values['mobile']:
       raise exceptions.ValidationError("Mobile is a mandatory field. "
                                        "Please provide a mobile number.")
- Same as before, it checks whether the 'mobile' field is provided in the values and if it's not empty. If not, it raises a validation error.
* result = super(ResPartner, self).write(values)
   return result
- Calls the original write method of the parent class (res.partner). This ensures that the standard behavior of updating a partner record is preserved while enforcing the custom validation.

Overriding Unlink Method:

As mentioned before, the unlink method is called when a record is deleted. Let's check an example for raising an exception when a non-admin user deletes a record by overriding the unlink method of (res.partner).
@api.multi
def unlink(self):
   # Check if the user is the admin
   if not self.env.user.has_group('base.group_erp_manager'):
       raise exceptions.UserError("Only the admin can delete partners.")
   # Call the original unlink method to delete the res.partner record
   result = super(ResPartner, self).unlink()
   return result
Explanation.
* @api.multi
def unlink(self):
- Decorates the unlink method, indicating that it's an Odoo API multi-record method. The unlink method is called when deleting records for the res.partner model.
* if not self.env.user.has_group('base.group_erp_manager'):
       raise exceptions.UserError("Only the admin can delete partners.")
- Checks if the current user has the admin privileges by checking if they belong to the 'base.group_erp_manager' group, Raises a user error if the user is not an admin.
* result = super(ResPartner, self).unlink()
   return result
- Calls the original unlink method of the parent class (res.partner). This ensures that the standard behavior of deleting a partner record is preserved while enforcing the custom logic.
Overriding the create, write, and unlink methods allows developers to customize the default behavior of record creation, modification, and deletion in a specific model without modifying the original core code.
To read more about override create, write, & unlink methods in Odoo 16, refer to our blog How to Override Create, Write, & Unlink Methods in Odoo 16


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment

 


whatsapp
location

Calicut

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

location

London

Cybrosys Limited
Alpha House,
100 Borough High Street, London,
SE1 1LB, United Kingdom

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