如何向odoo中没有属性的现有字段添加属性

问题描述

我在 sale.order 上有一个名为“payment_term_id”的现有字段,该字段在选择客户时填充,它使用 onchange 方法来填充它,我继承了该字段以添加一个属性,该属性使该字段在出现条件时为只读不满足。 但是,当我在销售订单上选择客户时,会填充“付款条款”字段,但是当我保存表单时,该字段变为空。如果没有这种继承和添加属性,它会按预期工作。 这是我的代码

<xpath expr="//field[@name='payment_term_id']" position="attributes">
           
            <attribute name="attrs">{'readonly': [('credit_group','=',False)]}</attribute>
 </xpath>

这是模型中的 credit_group 字段,如果用户有特定的组,则该字段仅分配 True 或 False。

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

    credit_group = fields.Boolean(compute='_compute_credit_group')

    @api.multi
    def _compute_credit_group(self):
        group = self.env.user. \
            has_group('name_of_module.group_name')
        for rec in self:
            rec.credit_group = group

解决方法

试试这个。只读字段不保存数据。如果你想保存只读字段的数据,你需要使用force_save。

<xpath expr="//field[@name='payment_term_id']" position="replace">
           
    <field name="payment_term_id" attrs="{'readonly': [('credit_group','=',False)]}" force_save='1'/>
    </xpath>