How to Override an Existing Controller in Odoo 14

How to Override an Existing Controller in Odoo 14

3 minutes, 25 seconds Read

In Odoo, ‘Controllers’ are utilized to design the frontend modules. These frontend modules are connected with the backend modules. Overriding is the property of a class to change the performance given by one of its base classes. It is used to differ in programming logic. We can override an alive controller in Odoo.
For working with controllers, firstly you have to create a folder ‘controllers’ inside the module,  add this folder inside the init file. We should add a python file that is an init and others to define controller methods and their properties. The module structure will look like the below image

how-to-override-an-existing-controller-odoo-14-cybrosys

To override a controller, you have to create a subclass to define existing functions. Now select a function from the controller for overriding from the addons.
For better understanding, I have selected the following Carousel Recently viewed function for overriding.
def _get_products_recently_viewed(self):
   """
   Returns list of recently viewed products according to current user
   """
   max_number_of_product_for_carousel = 12
   visitor = request.env['website.visitor']._get_visitor_from_request()
   if visitor:
    excluded_products = request.website.sale_get_order().mapped('order_line.product_id.id')
    products = request.env['website.track'].sudo().read_group(
        [('visitor_id', '=', visitor.id), ('product_id', '!=', False), ('product_id.website_published', '=', True), ('product_id', 'not in', excluded_products)],
        ['product_id', 'visit_datetime:max'], ['product_id'], limit=max_number_of_product_for_carousel, orderby='visit_datetime DESC')
    products_ids = [product['product_id'][0] for product in products]
    if products_ids:
        viewed_products = request.env['product.product'].with_context(display_default_code=False).browse(products_ids)
        FieldMonetary = request.env['ir.qweb.field.monetary']
        monetary_options = {
            'display_currency': request.website.get_current_pricelist().currency_id,
        }
        rating = request.website.viewref('website_sale.product_comment').active
        res = {'products': []}
        for product in viewed_products:
            combination_info = product._get_combination_info_variant()
            res_product = product.read(['id', 'name', 'website_url'])[0]
            res_product.update(combination_info)
            res_product['price'] = FieldMonetary.value_to_html(res_product['price'], monetary_options)
            if rating:
                res_product['rating'] = request.env["ir.ui.view"]._render_template('portal_rating.rating_widget_stars_static', values={
                    'rating_avg': product.rating_avg,
                    'rating_count': product.rating_count,
                })
            res['products'].append(res_product)
        return res
   return {}
So at first, we need to import  this from the library
from odoo.addons.website_sale.controllers.main import WebsiteSale
from odoo.http import request
Now we need to paste this function into our subclass, and you can make the required changes inside it. At present inside the function, the maximum number of products displayed in the carousel is 12. We will change it to 10 as shown below.

how-to-override-an-existing-controller-odoo-14-cybrosys

If you check the website now, you can see only 10 products in the carousel as in the following image.
how-to-override-an-existing-controller-odoo-14-cybrosys

While overriding a controller we should consider the following things.
* We have two ways for overriding an existing controller in odoo. 
    – Function Replacing: We can select a controller or function and paste it into our subclass, now you can make the required changes inside it
    – Supering a function: The super function is used to  return methods and properties of a parent class.
* We need to import the controller classes like below.
from odoo.addons.website_sale.controllers.main import WebsiteSale
* If we have to get values or modify them, by rendering the template we can get it with “qcontext” or **kwargs. Q context helps to get the values returned from the original controller and if needed we can modify the value.
* Sometimes If you are looking to override a controller that has a route, it may cause an issue. so, we will have to specify the route inside the subclass and then you can make changes inside it.
For example,

how-to-override-an-existing-controller-odoo-14-cybrosys

So in the above example, we have considered all the points discussed above for overriding a controller. Here we have changed a product’s name using Q context.
[wpcc-iframe loading=”lazy” allowfullscreen=”” allow=”autoplay *; encrypted-media *” src=”https://cdn.iframe.ly/1G9BSxU?iframe=card-small&v=1&app=1″ style=”border: 1px solid rgb(222, 222, 222); box-shadow: rgba(0, 0, 0, 0.06) 0px 1px 3px;”]

Similar Posts

Leave a Reply

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