Skip to Content
Menu
This question has been flagged
1 Atsakyti
341 Rodiniai

Hello,

In Odoo 15, I have a form view with the following code to make the company_id field mandatory:

<xpath expr="/form/sheet//field[@name='company_id']" position="attributes"> <attribute name="required">1</attribute> </xpath>

This works as expected.

Now, I want to automatically populate the company_id field with the current user's company when creating a new record, using XML only. I've tried adding the following:

<xpath expr="/form/sheet//field[@name='company_id']" position="attributes"> <attribute name="required">1</attribute> <attribute name="context">{'default_company_id': company_id}</attribute> </xpath>

However, this does not auto-fill the field as intended.

Is there a way to achieve this purely through XML in Odoo 15? Or is it necessary to implement this functionality using Python code?

Portretas
Atmesti
Best Answer

Hi,


Options you have,

1- Pure XML (without Python)

       You can only pass a static ID in the context attribute, e.g.:

                <field name="company_id" context="{'default_company_id': 1}"/>


-That will always default to company with ID 1, not the current user’s company.

-If your use case is always one company, this works.


2- Dynamic Default (Python needed)


    To use the current user’s company, you need Python because only Python can evaluate self.env.user.company_id.id.


    Example:


              company_id = fields.Many2one(

    'res.company',

    string="Company",

    default=lambda self: self.env.user.company_id.id,

    required=True,

)


- This ensures that whenever a new record is created, the company field is prefilled with the user’s company.


* With XML alone, you can only set a static default company.

* If you want the company to be the current user’s company, you must use Python (field default or default_get).


Hope it helps

Portretas
Atmesti
Related Posts Replies Rodiniai Veikla
1
kov. 25
1957
0
lapkr. 24
1842
0
birž. 24
1821
1
birž. 24
2337
1
gruod. 23
1697