Search code examples
odoo

How can i add a selection field of companies?


I want the add a selection field to my model. In this selection i want the see companies. I tried something like this but didn't work.

res_comp = fields.Many2one(comodel_name="res.company", string="TEST")
asd = fields.Selection(related="res_comp", readonly=False)

How Can I do someting like that.

And I have a one problem too. For example user select a company "A". I want the use this selection "A" inside of function. How can i use this. For example.

res_comp = fields.Many2one(comodel_name="res.company", string="TEST")
asd = fields.Selection(related="res_comp.name", readonly=False)

def test_func(self):
    print(asd)

But it's can't print the asd.

I need help about this two problem. Thank you for time.


Solution

  • Odoo will check the type consistency when setting up the related field

    You should see the following error in the log:

    TypeError: Type of related field MODEL_NAME.asd is inconsistent with res.company.name
    

    You can use a method to get the list of companies and set the selection values

    Example:

    def _get_companies(self):
        return [(str(c['id']), c['name']) for c in self.env['res.company'].search_read([], ['name'])]
    
    asd = fields.Selection(selection=_get_companies, string="TEST")
    

    To access the selection field inside a method, you need to use the record reference (self):

    def test_func(self):
        selected_company_id = self.asd
    

    When you access the selection field Odoo will return the selection key and in the example above, it will return the company ID

    To get the selection label you can use the fields_get method to get the field definition and use the selection attribute to get the field label of the corresponding selection key (self.asd)

    Example:

    def test_func(self):
        fields = self.fields_get(allfields=['asd'])
        asd = fields['asd']
        selection = asd['selection']
        asd_label = dict(selection)[self.asd]
    

    There is a selection widget that you can use with a many2one field to allow the selection of companies.

    You have just to set the field widget attribute to selection in the view definition

    Example

    <field name="res_comp" widget="selection"/>