Odoo v11中如何添加关联自定义报表的头部打印按钮?
解决Odoo会计模块自定义报表按钮添加失败的问题
看起来你已经成功创建了自定义报表,但在表单头部添加关联按钮时遇到了问题。问题主要出在按钮的配置上——你当前的按钮使用了type="object"但没有对应的Python方法,而且没有正确关联到你的自定义报表。下面是两种可行的解决方案:
方案一:直接关联报表Action(无需Python代码)
这种方法最直接,不需要编写额外的Python逻辑,直接通过报表的XML ID触发打印动作:
修正你的视图继承代码,将按钮配置改为:
<record id="my_invoice_form_inherit" model="ir.ui.view"> <field name="name">account.invoice.form.custom.button</field> <field name="model">account.invoice</field> <field name="inherit_id" ref="account.invoice_form"/> <field name="arch" type="xml"> <!-- 在默认打印按钮后添加自定义按钮 --> <button name="invoice_print" position="after"> <button name="%(custom_report_module.account_invoices)d" string="Factura pre-impresa" type="action" class="oe_highlight" help="Imprimir Factura pre-impresa" /> </button> </field> </record>
关键修改点:
type="action":告知Odoo这是触发一个Action而非对象方法name="%(custom_report_module.account_invoices)d":通过模块名+报表ID的格式引用报表自动生成的Action,这里custom_report_module是你的模块名,account_invoices是你定义的报表IDclass="oe_highlight":让按钮和Odoo默认打印按钮样式保持一致(高亮显示)string和help:匹配你报表的名称和提示信息
方案二:通过Python方法触发报表(适合需要额外逻辑的场景)
如果你需要在打印前添加一些业务逻辑(比如判断发票状态、权限校验等),可以通过继承account.invoice模型添加自定义方法:
- 在你的模块中添加Python代码(例如
models/account_invoice.py):
from odoo import models, api, exceptions class AccountInvoice(models.Model): _inherit = 'account.invoice' def print_custom_preprinted_invoice(self): # 确保只处理单条记录 self.ensure_one() # 可添加自定义逻辑,比如状态校验 if self.state not in ('open', 'paid'): raise exceptions.UserError("Solo se puede imprimir facturas en estado Abierto o Pagado") # 触发自定义报表 return self.env.ref('custom_report_module.account_invoices').report_action(self)
- 然后修改视图继承中的按钮配置:
<record id="my_invoice_form_inherit" model="ir.ui.view"> <field name="name">account.invoice.form.custom.button</field> <field name="model">account.invoice</field> <field name="inherit_id" ref="account.invoice_form"/> <field name="arch" type="xml"> <button name="invoice_print" position="after"> <button name="print_custom_preprinted_invoice" string="Factura pre-impresa" type="object" class="oe_highlight" help="Imprimir Factura pre-impresa" /> </button> </field> </record>
最后需要注意的事项:
- 模块依赖:确保你的模块
__manifest__.py中的depends包含['account'],否则会找不到会计模块的视图和模型 - 升级模块:修改完代码后,一定要在Odoo后台升级你的模块,清除缓存,否则修改不会生效
- 权限检查:确认当前用户拥有该自定义报表的访问权限,以及按钮所在视图的权限
- 视图ID正确性:如果你的Odoo版本较新(比如14+),会计发票的表单视图ID可能是
account.view_move_form而非account.invoice_form,需要根据实际版本调整inherit_id的引用
内容的提问来源于stack exchange,提问作者Hernan Chaparro
相关产品推荐
相关产品推荐

