so the idea is when i change the product, it checks on the stock available on the current branch, if none, it raises error that there are no stock
expected behavior: an error is raised when no stock is available on selected product and the record won't be added to tree view if no stock available
current behavior: the error is raised when no stock is available on selected product yet the record still gets added to the one2many tree view
code below
# -*- coding: utf-8 -*-
from docutils.nodes import line
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError
class CustomTransRequest(models.Model):
_name = 'custom.trans.request'
_description = 'Transfer Request'
user_id = fields.Many2one('res.users', string='Salesperson', default=lambda self: self.env.user)
branch_from_id = fields.Many2one('custom.branch', string="From", required=True)
branch_to_id = fields.Many2one('custom.branch', string="To", required=True)
product_ids = fields.One2many(comodel_name="custom.trans.line", inverse_name="request_id", string="Products",
required=False, )
class CustomTransLine(models.Model):
_name = 'custom.trans.line'
_description = 'Transfer Request Line'
branch_from_id = fields.Many2one(comodel_name="custom.branch", string="Branch", )
request_id = fields.Many2one("custom.trans.request", string="Request ID", )
product_id = fields.Many2one("custom.product", string="Product", required=True, )
qty = fields.Integer(string="Qty")
@api.onchange('product_id')
def onchange_product(self):
if self.product_id:
for rec in self:
selected_lines = rec.env['custom.branch.line'].search(
['&', ('product_id', '=', rec.product_id.id), ('branch_id', '=', rec.branch_from_id.id)]).mapped(
'qty')
if not selected_lines:
raise ValidationError(
_('Current branch has ZERO stock on this product, Please select an available Product'))
If you don't want record into one2many field, set product_id=False
. And return validation dictionary.
Try with following code.
@api.onchange('product_id')
def onchange_product(self):
if self.product_id:
res = {}
selected_lines = rec.env['custom.branch.line'].search(
['&',
('product_id', '=', self.product_id.id),
('branch_id', '=', self.branch_from_id.id)]).mapped('qty')
if not selected_lines:
self.product_id = False
res['warning'] = {'title': _('ValidationError'),
'message': _(
'Current branch has ZERO stock on this product, '
'Please select an available Product')}
return res