
Learn how to add stat buttons in Odoo form views to display metrics or counts, offering users quick insights and access to related records.
Adding stat buttons in Odoo is a great way to provide a quick summary or key metrics directly in the form view. Stat buttons are often used to display information like record counts, totals, or other calculated values. They appear as clickable buttons in the top of the form view, allowing users to easily access related data.
In Odoo, stat buttons are designed to show numeric summaries, counts, or key statistics of related records. These buttons can be configured to show totals, counts of related records, or any other computed information. They are usually displayed at the top of the form view, allowing users to click on them to access the related data.
To create stat buttons, you typically need to use the following elements:
Here is how you can add a simple stat button to a form view in Odoo:
First, define a computed field in your model. For example, let’s create a computed field to count the number of related records:
<from odoo import models, fields>
class CustomModel(models.Model):
_name = 'custom.model'
order_count = fields.Integer(string="Order Count", compute="_compute_order_count")
def _compute_order_count(self):
for record in self:
record.order_count = self.env['sale.order'].search_count([('partner_id', '=', record.id)])
In this code:
Next, you need to add the stat button to your form view XML:
<record id="view_custom_model_form" model="ir.ui.view">
<field name="name">custom.model.form</field>
<field name="model">custom.model</field>
<field name="arch" type="xml">
<form string="Custom Model">
<header>
<button name="action_view_orders" type="object" class="oe_stat_button">
<field name="order_count" widget="statinfo" icon="fa fa-shopping-cart"/>
</button>
</header>
</form>
</field>
</record>
Explanation of the XML structure:
If you want the stat button to perform an action (e.g., open a related records view), you can add a method:
<from odoo import models, fields>
class CustomModel(models.Model):
_name = 'custom.model'
def action_view_orders(self):
return {
'type': 'ir.actions.act_window',
'name': 'Sales Orders',
'view_mode': 'tree,form',
'res_model': 'sale.order',
'domain': [('partner_id', '=', self.id)],
}
In this example, the action_view_orders method opens the related sale.order records associated with the current model record.
Using stat buttons is an effective way to display key metrics directly on the form view in Odoo, enhancing the user experience by offering quick and actionable insights. With a few simple steps, you can add dynamic buttons to display calculated data and provide direct access to related records.
Your email address will not be published. Required fields are marked *