我在员工和部门表格中有两个选择框字段。当我根据员工的department_id选择员工时,我想自动选择部门。
这是我的.py代码(Odoo 11)
class HrExpenseExpense(models.Model):
_inherit = "hr.expense"
department_expense_group = fields.Selection(
string='Department Expense Group',
related='department_id.expense_group',
readonly=True,
)
department_id = fields.Many2one('hr.department', string='Department',
states={'post': [('readonly', True)], 'done': [('readonly', True)]})
@api.onchange('employee_id')
def onchange_employee_id(self):
department_id = [x.id for x in self.employee_id.department_id]
return {'domain': {'department_id': [('id', 'in', department_id)]}}
和xml视图文件:
<xpath expr="//field[@name='employee_id']" position="after">
<field name="department_expense_group" invisible="1" />
<field name="department_id" invisible="0"/>
</xpath>
正在工作,但是问题是这样;当我选择一名员工时,部门选择框会自动更新,但会自动触发,但不会自动选择。单击后将其填充到Selectbox的列表中。必须根据员工的选择自动选择它。
答案 0 :(得分:1)
您只需更改字段department_id
的过滤器,而必须将其设置为self即可满足您的要求。而且,您正在循环访问单个记录字段(employee_id.department_id
),这里有点夸张了。
@api.onchange('employee_id')
def onchange_employee_id(self):
if self.employee_id:
department = self.employee_id.department_id
# set department
self.department_id = department
# don't allow other departments
return {'domain': {'department_id': [('id', '=', department.id)]}}
else:
# empty department
self.department_id = False
# allow other departments
return {'domain': {'department_id': [('id', '!=', False)]}}