Enable Dark Mode!
how-to-use-fields-get-to-modify-field-properties-in-odoo-17.jpg
By: Aiswarya JP

How to Use fields_get() to Modify Field Properties in Odoo 17

Technical

In Odoo development, understanding how to change field properties dynamically can greatly enhance the flexibility and functionality of your modules. The fields_get() is a useful method that allows developers to retrieve and modify metadata of fields defined in Odoo models.

The fields_get() will actually return the definition of each field in a model. The returned value is a dictionary (indexed by field name) of dictionaries. The _inherits'd fields are included. The string, help, and selection (if present) attributes are translated.

The fields_get() will be useful in scenarios where;

1) Hide fields from Custom Filter and Custom Group by menu in search view based on conditions.

2) Hiding or making fields readonly based on user roles or other conditions.

3) Conditionally preventing the field from being exported, etc…

Let’s start with a basic example of showing how we can use fields_get() method in a model.

from odoo import models
class ProductTemplate(models.Model):
_inherit = 'product.template'
def fields_get(self, fields=None):
           res = super(ProductTemplate, self).fields_get(fields=fields)
           if 'default_code' in res:
                     res['default_code']['string'] = 'Product Code.'
                                           # Add more modifications as needed
               return res

The above code demonstrates how to use fields_get() to modify the string of a field named 'default_code'.

Now, let’s explore how to use fields_get() to modify various attributes of a field in Odoo.

1. Set a field as non-exportable based on condition.

@api.model
def fields_get(self, allfields=None, attributes=None):
    res = super().fields_get(allfields, attributes)
    if self._context.get('default_move_type') == 'out_invoice':
                if res.get('payment_state'):
                  res['payment_state']['exportable'] = False
    return res

In this example, 'payment_state' field is made non-exportable if the move_type is ‘out_invoice’. Likewise, you can replace the condition as per your requirement.

2. Hide field from Groupby/Filters based on condition.

@api.model
def fields_get(self, allfields=None, attributes=None):
     res = super().fields_get(allfields, attributes)
    if self.env.company.id != 1:
              if res.get('origin'):
            res['origin']['sortable'] = False
                       res['origin'][searchable’] = False
    return res

3. Change field string based on condition

@api.model
def fields_get(self, allfields=None, attributes=None):
    res = super().fields_get(allfields, attributes)
    if self._context.get('location') and isinstance(self._context['location'], int):
               location = self.env['stock.location'].browse(self._context['location'])
              if location.usage == 'supplier':
            if res.get('virtual_available'):
                res['virtual_available']['string'] = _('Future Receipts')
            if res.get('qty_available'):
                res['qty_available']['string'] = _('Received Qty')
               elif location.usage == 'internal':
            if res.get('virtual_available'):
                res['virtual_available']['string'] = _('Forecasted Quantity')
                   —--------------------------------------

4. Modify the domain of a field based on condition

   @api.model
def fields_get(self, allfields=None, attributes=None):
    fields = super().fields_get(allfields, attributes)
    if self.env['account.analytic.plan'].check_access_rights('read', raise_exception=False):
        project_plan, other_plans = self.env['account.analytic.plan']._get_all_plans()
        for plan in project_plan + other_plans:
            fname = plan._column_name()
            if fname in fields:
                                fields[fname]['domain'] = f"[('plan_id', 'child_of', {plan.id})]"
    return fields

Like the above mentioned examples, you can modify all other field attributes using the fields_get().

Using fields_get() in Odoo can significantly enhance customizations and allow dynamic adjustments of field properties based on user context or business logic which leads to a more flexible and user-centric experience.

To read more about What is Property Field in Odoo 16, refer to our blog What is Property Field 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

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