Skip to Content
Meniu
Trebuie să fiți înregistrat pentru a interacționa cu comunitatea.
Această întrebare a fost marcată
1 Răspunde
521 Vizualizări

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?

Imagine profil
Abandonează
Cel mai bun răspuns

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

Imagine profil
Abandonează
Related Posts Răspunsuri Vizualizări Activitate
1
mar. 25
2072
0
nov. 24
1945
0
iun. 24
1885
1
iun. 24
2412
1
dec. 23
1754