In Odoo, when working with Sales Order lines and ensuring they are saved automatically while the Sales Order is in editing mode, you can consider the following approaches:
1. Using @api.onchange to Auto-Save Order Lines
If you want the Sales Order lines to be saved automatically when modified, you can use the @api.onchange decorator in your custom module:
python
CopyEdit
from odoo import models, fields, api
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
@api.onchange('product_id', 'product_uom_qty', 'price_unit')
def _auto_save_order_line(self):
if self.order_id and self.order_id.state in ['draft', 'sent']:
self.order_id.write({'order_line': [(1, self.id, {
'product_id': self.product_id.id,
'product_uom_qty': self.product_uom_qty,
'price_unit': self.price_unit,
})]})
-
This triggers an automatic save when changes are made to the product_id, product_uom_qty, or price_unit.
2. Overriding the Write Method
If you want to automatically save sales order lines when edited, override the write method:
python
CopyEdit
class SaleOrder(models.Model):
_inherit = "sale.order"
def write(self, vals):
res = super(SaleOrder, self).write(vals)
if 'order_line' in vals:
for line in self.order_line:
line.write({}) # Forces a save
return res
-
This ensures that when the Sales Order is edited and saved, the Sales Order lines are also saved.
3. Using @api.depends with stored=True to Persist Changes
Another approach is to make fields stored so that Odoo automatically saves changes:
python
CopyEdit
class SaleOrderLine(models.Model):
_inherit = "sale.order.line"
total_price = fields.Float(compute="_compute_total_price", store=True)
@api.depends('product_uom_qty', 'price_unit')
def _compute_total_price(self):
for line in self:
line.total_price = line.product_uom_qty * line.price_unit
-
The store=True ensures that when quantity or price changes, the data is persisted automatically.
4. Enabling Auto-Save in the Frontend (JavaScript)
For an immediate update in the UI, override the sale.order form view in XML and add autosave="true":
xml
CopyEdit
<record id="view_order_form_inherit" model="ir.ui.view">
<field name="name">sale.order.form.inherit</field>
<field name="model">sale.order</field>
<field name="inherit_id" ref="sale.view_order_form"/>
<field name="arch" type="xml">
<xpath expr="//form" position="attributes">
<attribute name="autosave">true</attribute>
</xpath>
</field>
</record>
-
This ensures the form saves changes automatically.
this is perfect thanks