Bỏ qua để đến Nội dung
Menu
Câu hỏi này đã bị gắn cờ
1 Trả lời
422 Lượt xem

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?

Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

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

Ảnh đại diện
Huỷ bỏ
Bài viết liên quan Trả lời Lượt xem Hoạt động
1
thg 3 25
1991
0
thg 11 24
1857
0
thg 6 24
1827
1
thg 6 24
2344
1
thg 12 23
1711