跳至內容
選單
此問題已被標幟
1 回覆
276 瀏覽次數

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?

頭像
捨棄
最佳答案

Hello Uday,



  To automatically set the company_id field in a form view to the current user's company in Odoo 15 using XML, you'll need to adjust the context attribute correctly. Unfortunately, your current approach does not dynamically fetch the user's company. Instead, try using the following method:

  1. Ensure your form view XML structure is correct and ready for modification.

  2. Modify the company_id field context attribute like this:
    <field name="company_id" context="{'default_company_id': user.company_id.id}" />
  This snippet correctly references the current user's company ID, setting it as the default value for the company_id field when creating a new record.

  3. Apply the changes and update the module. Test the form view by creating a new record to ensure the company_id field is automatically populated with the current user's company.


For personalized assistance:
https://www.pragtech.co.in/contact-us-mql.html

頭像
捨棄
作者

Thanks for the reply! I have been doing it with the following code so far, but I didn't know about the default_get function. Could you share more functions like this?

python
class ProductProduct(models.Model):
_inherit = 'product.product'

@api.model
def default_get(self, fields_list):
defaults = super(ProductProduct, self).default_get(fields_list)
if 'company_id' in fields_list:
defaults['company_id'] = self.env.company.id
return defaults

相關帖文 回覆 瀏覽次數 活動
1
3月 25
1941
0
11月 24
1834
0
6月 24
1816
1
6月 24
2331
1
12月 23
1694