Skip to Content
Menu
This question has been flagged

I created 2 fields inside the stock.move.line inside transfers : The first one is many2one field and I need to populate it automatically if the second customized boolean field is checked. The field I need to populate with is the product_id which is already found in the lines. Any Ideas? Here is my code: 


@api.onchange('product_id')
def relate_alternatives(self):
for rec in self:
if rec.alternative_delivery_item==True:
rec.product_alternative=rec.product_id


I don't need an onchange function, I need when checking the box, I need the new many2one field to be filled automatically, at the same time I need when changing the product_id again not affect the other many2one field I created. Thanks

Avatar
Discard
Best Answer

You need a computed field mechanism. A computed field is a way of calculating the information dynamically. For example:


product_alternative = fields.Many2one('product.product', string='Product', compute="_computed_product_id")


The "compute" attribute execute a method from your class where calculate what you need in instance. Try this method:


@api.depends('alternative_delivery_item')
def _computed_product_id(self):
for rec in self:
if rec.alternative_delivery_item == True:
rec.product_alternative = rec.product_id


The "computed" field is calculated in execution time so it's important understand if you wish stored this data, so you'll need add a attribute called stored=True. In this case, you can be get this data from your database.

You can found more references in Cybrosys blog post about computed fields.

Avatar
Discard
Author

Thank you, I tried this code but I got this error when I enter a transfer: Something went wrong !
×
stock.move.line(142974,).product_alternative

You can send a log return here to we analyse easily. Or send the user error return completely

Author

That's the error: 'stock.move.line(142974,).product_alternative', None and the one I sent before

Try remove the depends decorator

I done a little correction in api.depends decorator. I expect this is the solution. Try this:

@api.depends('alternative_delivery_item')

Author

@api.onchange('product_id')
def _computed_product_id(self):
# self.ensure_one()
for rec in self:
if rec.alternative_delivery_item == True:
rec.product_alternative = rec.product_id

That is the new update and its working fine. But I need the onchange function to execute only once. Is there any condition that can help me limit this?

You will can create a field where be created a execution condition to method. For example:

product_alternative_processed = fields.Boolean(string='Processed Product Alternative', deafult=False)

Every time you run this method check if the field has been calculated. Otherwise, you will edit the field.

Related Posts Replies Views Activity
1
Mar 23
1244
0
Aug 19
2487
1
Dec 15
5133
1
Oct 22
2424
1
Oct 20
6195