Skip to Content
Menu
This question has been flagged
1 Reply
3320 Views

How can I add create (one or more sale order lines) upon changing values in one field of another / an existing line of the same order ?

I know I can use new() which is working great, except that I need to save it directly to the DB (I need it's ID in further processing), so I need to use create()

The record it's actually created in the DataBase but it's not visible to the user until user manually saves the SO or reloads the page (SO already in edit mode)

How can I add the new record into the tree view ?

Avatar
Discard
Author Best Answer

I've almost found a proper way, but it still has some issues

With the following code inside `sale_order._onchange_order_line()` I could create multiple new records (saved into the DB) and add them into user's editing tree view

class SaleOrder(models.Model):
_inherit = 'sale.order'

@api.onchange('order_line')
def _onchange_order_line(self):
   # store here new lines that we might create below (we use an empty 'sale.order.line' recordset as default value in order to easily add records to it as we need ...)
new_lines = self.env['sale.order.line']

  # if we need to add one or multiple sale order lines in the DB
new_line = self.order_line.create({
'order_id': self._origin.id,
'product_id': 10, # some product.product ID,
})

# trigger some methods to update all the rest of the values
new_line.product_id_change()

# add new line to the new_lines recordset
new_lines |= new_line

# some other processing, even adding couple of more lines like above ...

# at the end, in case we need to send back the newly created lines ...
if new_lines:
# combine existing order_line with the new lines
all_lines = self.order_line + new_lines

return {
'value': {
'order_line': all_lines
}
}

But, the new problems I face now, are:

  • if I remove any of this newly created records which I'm injecting into the view (before save) and then save, it's looking ok (they're removed from the view) except that they're NOT actually deleted from the DB (if I save or reload they get back in the view)

  • if I discard the changes all these records are removed from the view which normally it shouldn't as they're save into the DB (not phantom records) and the user get's confused but actually they're still in the DB (on refresh they get back into the view)

If I manually save the order as soon as those lines are added and edit it back everything it's ok

So I am very close but still missing a small detail I guess ...

Same result with the same issues I have also if I just connect the new records like this (instead of returning the new combined lines like above):

self.order_line = [(4, ln.id, 0) for ln in new_lines]

.

Avatar
Discard