Override the Create, Write, & Unlink Methods in Odoo 17

HISHAM
April 17, 2024
unlink-methods-in-odoo

With the help of the “create,” “write,” and “unlink” methods, developers can precisely manage the addition, modification, and removal of records on the flexible open-source ERP platform Odoo. We will discuss the importance of overriding these methods in Odoo 17. In this blog post and how this customization gives developers the ability to mold the data lifecycle to meet specific business requirements.

The “create,” “write,” and “unlink” functions stand for important phases of a record’s existence in the database:

Create Method: Called when a model is updated with a new record.

Write Method: Initiated whenever an already-existing record is updated or changed.

Unlink Method: carried out whenever a record is removed or unlinked from its parent model.

Overriding Create Method: As previously indicated, when a new record is created for a particular model, the Create() method is called. For instance, by overriding the res. the “mobile” field is now required for the partner model’s creation method.                                                                                                                                                                                                 

class ResPartner(models.Model):

_inherit = "res.partner"

       @api.model

       def create(self, values):

       # Check if the 'mobile' field is provided in the values

       if 'mobile' is not in values or not values.get('mobile'):

              raise exceptions.ValidationError("Mobile is a mandatory field. "

                           Please provide a mobile number.")

       # Call the original and create a 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” – This indicates that the standard Odoo res. partner model is the model this model (ResPartner) is inheriting from. A model can be inherited from its parent model by using the “_inherit” model constraint.

*@api.model def create(self, values): – Indicates that this is an Odoo API model method by decorating the create method. When a new record for the res. partner model is created, the create method is called.

* If the value “mobile” is absent or nonexistent.obtain(‘mobile’): raise exceptions.ValidationError(“Mobile is a mandatory field. “); * “Please provide a mobile number.” * – Verifies that the mobile field is present in the values and is not empty. It raises a validation error otherwise.

* partner equals super(self, ResPartner).generate (values)

       return partner: This invokes the parent class’s original create method (res. partner). This makes sure that while enforcing the custom validation, the standard behavior of creating a partner is maintained.

 Overriding Write Method:

As previously indicated, when a record is updated, the “write” method is triggered. We overrode the create method and made the mobile field mandatory in the previous instance. Therefore, even though we are unable to add a mobile field when creating a new record, we are still able to update an existing record without doing so. For example, we should override the write method to limit this.

@api.multi

def write(self, values):

       # Check if the '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

Code description:

* @api.multi def write(self, values):

– Indicates that the write method is a multi-record Odoo API method by decorating it. When updating records for the res. partner model, the write method is invoked.

* raise exceptions if’mobile’ is present in values but not values[‘mobile’].ValidationError(“Please provide a mobile number.”); “Mobile is a mandatory field.”

– Just like previously, it verifies that the values include the “mobile” field and that it is not empty. It raises a validation error otherwise.

* outcome = super(self, ResPartner).write (values)

   return result – Calls the parent class’s original write method (res. partner). This guarantees that the custom validation is enforced while maintaining the standard behavior of updating a partner record.

Overriding Unlink Method:

As previously stated, when a record is deleted, the unlink method is called. Now let’s look at an example of raising an exception when a non-admin user overrides the (res. partner) unlink method to delete a record.

@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): – Indicates that the unlink method is a multi-record Odoo API method by decorating it. When deleting records for the res. partner model, the unlink method is invoked.

* Raise exceptions

if self.env.user.has_group(‘base.group_erp_manager’) is false.UserError(“Partners can only be deleted by the admin.”)

– Determines whether the current user is an admin by looking up whether they are a member of the ‘base.group_erp_manager’ group. if the user is not an administrator, raises a user error.

* outcome = super(self, ResPartner).unlink()

   return result: Invokes the parent class’s original unlink function (res. partner). This guarantees that the custom logic is enforced while maintaining the standard behavior of deleting a partner record.

 Without changing the original core code, developers can alter the default behavior of record creation, modification, and deletion in a particular model by overriding the create, write, and unlink methods in Odoo.                                                                                                                                                                                                                   

"Unlock the Full Potential of Your Business with Odoo ERP!"

"Get a Cost Estimate for Your ERP Project, Absolutely FREE!"

Get a Free Quote

Leave a Reply

Your email address will not be published. Required fields are marked *