如何只允许在 many2one 字段中创建选项

How to allow only create option in many2one field

如何隐藏 many2one 字段中的所有项目。我只想让用户创建一个新的付款期限。 我们在 account_invoice.py:

account 模块中有这段代码
class AccountInvoice(models.Model):
    _name = "account.invoice"
    payment_term_id = fields.Many2one('account.payment.term', 
                                       string='Payment Terms', 
                                       oldname='payment_term',
                                       readonly=True, 
                                       states={'draft': [('readonly', False)]})

account_invoice_view.xml中我们有:

<field name="payment_term_id" 
       options="{'no_create': True}" 
       attrs="{'invisible': [('payment_term_id','=',False)]}"/>

我试过这段代码 {'no_open':True} 但它没有用。

如果您想隐藏列表中的所有元素,请尝试添加始终为 False:

的域
<field name="id" />
<field name="payment_term_id" 
       domain="[('id', '=', -1)]"
       attrs="{'invisible': [('payment_term_id','=',False)]}"/>

options="{'no_create': True}"如果我理解得很好,你会得到与你想要的相反的结果

我想你会发现这个解决方案适合你:

建议在你的模型中添加一个字段,这个字段是 many2many 字段 包含在当前记录中创建的 payment_term_id 的列表。

 # this field is for technical purpose 
 create_payment_terms_ids = fields.Many2many(co_model='account.payment.term',
                                             relation='created_payment_rel',
                                             column1= 'invoice_id',
                                             column2= 'paymen_id',
                                             string='Created payment terms')

在此之后使用 onchange 方法来跟踪创建的付款并添加新的 此字段的付款条件

@api.onchange('payment_term_id')
def onchange_payment_terms(self):
    """ keep track of created payment from the current
        invoice and show only them in drop down list."""
    if self.payment_term_id:
        # keep list of old ids here
        payment_ids = self.create_payment_terms_ids and self.create_payment_terms_ids.ids or []
        # check if list payment is empty this means that this is the first created payment
        # second check if the selected payment is a new payment that is created 
        # if one of the two is true add the selected value to the list of payment
        if not self.create_payment_terms_ids or self.payment_term_id.id not in payment_ids:
            payment_ids.append(self.payment_term_id.id)
            self.create_payment_terms_ids = [(4, self.payment_term_id.id)]

        # if list is not empty we change the domain to show only payment that exist in the list
        # else we use a special domain to show empty set.
        domain = payment_ids and [('payment_term_id', 'in', payment_ids)] or [('id', '=', -1)]
        return {'domain': {'payment_term_id': domain}}

在您的视图中添加带有 visible = "1" 的新字段,您不会让用户看到它的值。 你需要把它放在视图中,因为你需要它在 onchange 事件中的值,如果你不把它放在你的 many2many 字段将永远是空的。

       <field name="create_payment_terms_ids" invisible="1"/>

并删除 options="{'no_create':False}" 这将删除下拉列表中的创建和编辑选项,而您不希望这样。

注意:当您在开发中时,请删除 invisible="1" 以查看 many2many 字段是否包含您拥有的付款列表 创建。