Ir al contenido
Menú
Se marcó esta pregunta
1 Responder
284 Vistas

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?

Avatar
Descartar
Mejor respuesta

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

Avatar
Descartar
Autor

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

Publicaciones relacionadas Respuestas Vistas Actividad
1
mar 25
1941
0
nov 24
1834
0
jun 24
1816
1
jun 24
2331
1
dic 23
1694