This question has been flagged
1 Reply
9513 Views

Hello,

I would like to set fields.Char size dynamically, registration number of an employee, e.g: 0001 or 0002, which is size of 4 here, so if the manager decided to set the size to 5 then I have to change it in code in that case, but the manager wants it to be in a parameter in the company settings so he could change it whenever he wants to.

I already tried:
case 1: defining size dynamically on python side

my_field = fields.Char(..., size=lambda self: self.get_dynamic_size())
# or
fields.Char(..., size=lambda self: get_dynamic_size(self))

case 2: set maxlength of the field in xml


​​​​<field name="my_field" attrs="{'max_length': uid.company_id.get_dynamic_size}"

But none of those actually works

My work around was defining an onchange function to correct the input but this doesn't give the same experience for the user as setting maxlength on the input field

Avatar
Discard
Best Answer

I liked the way you tried it first before asking the question. I appreciate your efforts and would try to help you.

You don't need to set dynamic size. You just need to create a configuration where your manager can set the size of the number.

Now, you just have to create a constraint which will check the size of the employee number and compare it with the value which is entered by manager in the configuration.

@api.constrains('emp_no')
def _check_emp_no(self):
if self.emp_no:
if len(self.emp_no) > self.user.company_id.get_dynamic_size:
raise ValidationError('Employee Number cannot be more than %s ' %self.user.company_id.get_dynamic_size)


Avatar
Discard
Author

Thanks for your reply, but isn't there a solution which could limit the user input like maxlength does? where it triggers live when user is typing the emp_no, not when the focus is lost on the input like in onchange or on creating/updating? ... But, if there isn't, then, this approach in my opinion is a lot better, I totally forgot there was @api.constrains lol, thank you buddy

AFAIK, there isn't a way to do it dynamically.

You can use onchange to show the warning message but it won't stop the execution, user will still be able to save the record.