Odoo V9中如何替换动态命名按钮并添加默认上下文?
解决Odoo V9中为动态name属性的按钮添加默认上下文的问题
在Odoo V9里碰到这种动态name属性的按钮修改需求确实有点棘手,毕竟官方弃用了字符串XPath搜索,没法直接靠动态值定位。不过别担心,我们可以利用按钮的其他固定属性组合来精准定位目标按钮,然后轻松添加自定义上下文。
方案1:替换整个按钮(适合需要修改多个属性的场景)
我们通过按钮的type、states、string这些不会变动的属性来写XPath定位,然后用position="replace"替换原按钮,同时加入需要的context属性。
直接上代码示例:
<record id="view_account_invoice_form_inherit" model="ir.ui.view"> <field name="name">account.invoice.form.inherit</field> <field name="model">account.invoice</field> <field name="inherit_id" ref="account.invoice_form"/> <field name="arch" type="xml"> <!-- 用固定属性组合定位目标按钮,避开动态name --> <xpath expr="//button[@type='action' and @states='open' and @string='Register Payment']" position="replace"> <!-- 保留原按钮的所有属性,新增context --> <button name="%(action_account_invoice_payment)d" type="action" states="open" string="Register Payment" groups="account.group_account_invoice" class="oe_highlight" context="{'default_your_field': your_value, 'default_another_field': another_value}"/> </xpath> </field> </record>
方案2:仅修改上下文属性(更简洁高效)
如果只是需要添加默认上下文,不需要改动按钮的其他属性,直接用position="attributes"来给原按钮添加或覆盖context属性就行,不用重写整个按钮:
<record id="view_account_invoice_form_inherit" model="ir.ui.view"> <field name="name">account.invoice.form.inherit</field> <field name="model">account.invoice</field> <field name="inherit_id" ref="account.invoice_form"/> <field name="arch" type="xml"> <xpath expr="//button[@type='action' and @states='open' and @string='Register Payment']" position="attributes"> <!-- 直接添加上下文,这里的键值对换成你需要的默认值 --> <attribute name="context">{'default_partner_id': partner_id, 'default_amount': amount_total}</attribute> </xpath> </field> </record>
关键注意点:
- 定位逻辑:一定要用固定属性组合,比如
type、states、string,这些值不会随动态动作ID变化,能确保XPath精准命中目标按钮。 - 上下文格式:按照Odoo的标准格式写,键名以
default_开头对应字段名,值可以是当前视图里的字段值(比如amount_total)或者固定值。 - 视图继承:记得继承原发票表单视图
account.invoice_form,不然你的修改不会生效哦。
内容的提问来源于stack exchange,提问作者drkpkg
相关产品推荐
相关产品推荐

