This question has been flagged
1 Reply
6526 Views

I have two models Parent and Child.  In the Parent form I am allowing the user to adding Childs based on the One2Many relation between Parent and Child. Then I need to prevent him from adding more than X number of Childs, how to achieve

 this 

I have two models Parent and Child. In the Parent form I am allowing the user to add Childs based on the One2Many relation between Parent and Child. Then I need to prevent from adding more than X number of Childs, how to achieve this?

Right now I am able to check the number of added childs using OnChange(). and the alert message appears to the user that he acceded the limit of childs.

Assume the limit is 3 childs, how can I do the following:

  1. After adding the 4 childs, show alert message (this already done),  then delete the last added child(s) that acceds the limit

  2. Or, once childs max limit achieved, hide the "Add an Item" link



Avatar
Discard
Best Answer

Hi Abu Faisal,

Should you create a pythonic constrain @api.constrains('One2many') and do a check on One2many field length using len() and raise warning.

Something like this, https://github.com/odoo/odoo/blob/9.0/addons/account/models/account_invoice.py#L1236

len(self.One2many_field) would give you records number and then you can raise warning.

Avatar
Discard
Author

Hi Rifakat, Thanks for helping me ;-) I successfully implemented the constrain, and now the user cannot save the submitted parent form if the child items accedes the limit. User should delete the extra child items manually. As you know the @api.constrain function called on form save, so do you know if I can even prevent adding more items before reaching the form saving? (I am able to show the warning after he adds but not able to delete the added child rows)

you right. constrain will be checked when saving the record while user has already added all items. you can also create @api.onchange('order_line'), to raise a warning, but as you may know, onchange would only raise warning and will not restrict user to add more items. In your case you will need @api.constrain() as well as @api.onchange(), constrain to restrict saving records, and onchange to warn user that he is doing wrong. Thanks.