Search code examples
inheritanceodooodoo-12

Override and Change the middle of a function Odoo


I would like to override a function called _cart_update which is in the website_sale module. But I want to change the middle of the function (I want to do something in the middle of the function code). So I tried to rewrite the function in my custom module and add the website_sale module as a dependency module (I rewrite the function without adding any super() calls). My function gets the function call. No problem with that. But there are other modules that override the same function with super() calls. Sadly, those functions will not be executed. But I want them to be executed.

Is there any issue with my work? or is there any other way to do this?

Thank you.


Solution

  • You can do a monkey patching:

    from odoo.addons import website_sale  # so we can update the method in the class
    # import any global variable that the method use directly from of website_sale
    # I think I covered all variable but in version 11, I don't know if they change it in 12
    from odoo.addons.website_sale.models.sale_order import _logger, ValidationError, request, UserError, _, api
    # import any thing you need to use in your custom code if there is
    
    @api.multi
    def _cart_update(self, product_id=None, line_id=None, add_qty=0, set_qty=0, attributes=None, **kwargs):
        # put the full code here
        # you don't need to call super because it will be the last one to call
        # it's like we defined it in the website_sale 
    
    # at the end replace the method in the class that was defined in the website_sale
    website_sale.models.SaleOrder._cart_update = _cart_update
    

    The only solution is to replace the method in the class because if you use super in one of the sub classes the original method will be executed.