Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odoo - add custom field attribute?

Is there a way to add custom field attribute in Odoo? For example every field has attribute help where you can enter message explaining the field for the user. So I want to add custom attribute, so that would change the way field acts for all types of fields.

I want to add into Field class, so all fields would get that attribute. But it seems no matter what I do, Odoo does not see that such attribute was added.

If I simply add new custom attribute like:

some_field = fields.Char(custom_att="hello")

Then it is simply ignored. And I need it to be picked up by method fields_get, which can return wanted attribute value (info what it does:

def fields_get(self, cr, user, allfields=None, context=None, write_access=True, attributes=None):
    """ fields_get([fields][, attributes])

    Return the definition of each field.

    The returned value is a dictionary (indiced by field name) of
    dictionaries. The _inherits'd fields are included. The string, help,
    and selection (if present) attributes are translated.

    :param allfields: list of fields to document, all if empty or not provided
    :param attributes: list of description attributes to return for each field, all if empty or not provided
    """

So calling it, does not return my custom attribute (it does return the ones originally defined by Odoo though).

I also tried updating _slots (with monkey patch or just testing by changing source code) attribute in Field class, but it seems it is not enough. Because my attribute is still ignored.

from openerp import fields

original_slots = fields.Field._slots

_slots = original_slots
_slots['custom_att'] = None

fields.Field._slots = _slots

Does anyone know how to properly add new custom attribute for field?

like image 833
Andrius Avatar asked Jun 10 '16 07:06

Andrius


1 Answers

Assuming v9

The result of fields_get is a summary of fields defined on a model, the code shows that it will only add the attribute if the description was filled. It will fetch the description of the current field by calling field.get_description

So in order to ensure that your attribute gets inserted into this self.description_attrs you will need to add an attribute or method that starts with _description_customatt (customatt part from your example) and will return the required data.

I've not run any tests for this but you can look at the code for the fields and their attributes what they actually return. For instance the help attribute description (src)

def _description_help(self, env):
  if self.help and env.lang:
    model_name = self.base_field.model_name
    field_help = env['ir.translation'].get_field_help(model_name)
    return field_help.get(self.name) or self.help
  return self.help
like image 162
Red15 Avatar answered Oct 18 '22 10:10

Red15