Odoo 12:采购订单佣金字段无法同步至创建账单的发票表单求助
Hey there! Let's break down what's going wrong here and fix it step by step:
1. You forgot to add the commission field to account.invoice
First off, even if you pass the commission value from the purchase order to the invoice, the account.invoice model doesn't have this field defined—so it won't store the value, and you definitely won't see it in the form view. Let's fix that first:
from odoo import models, fields, api, _ from odoo.exceptions import UserError class AccountInvoice(models.Model): _inherit = "account.invoice" commission = fields.Float(string='Commission', default=0)
You also need to add this field to the account.invoice form view so it shows up in the UI. Add this XML to your module:
<record id="view_account_invoice_form_inherit_commission" model="ir.ui.view"> <field name="name">account.invoice.form.inherit.commission</field> <field name="model">account.invoice</field> <field name="inherit_id" ref="account.invoice_form"/> <field name="arch" type="xml"> <!-- Adjust the position to where you want the field to appear --> <field name="reference" position="after"> <field name="commission" attrs="{'readonly': [('state', '!=', 'draft')]}"/> </field> </field> </record>
2. Your action_view_invoice method has API and logic issues
Your current method mixes old-style ORM (using cr, uid, pool) with new API decorators (@api.multi), and it's not returning the correct action to open the invoice view. Here's the corrected version that properly passes the commission value:
class ConfirmComm(models.Model): _inherit = "purchase.order" commission = fields.Float(string='Commission', required=True, default=0) @api.multi def action_view_invoice(self): self.ensure_one() # Call the original method to keep default behavior res = super(ConfirmComm, self).action_view_invoice() # Handle existing invoice or new invoice creation if res.get('res_id'): # If invoice already exists, update its commission value invoice = self.env['account.invoice'].browse(res['res_id']) invoice.write({'commission': self.commission}) else: # If creating a new invoice, add commission to default values context = res.get('context', {}) default_vals = context.get('default', {}) default_vals['commission'] = self.commission res['context'] = dict(context, default=default_vals) return res
Key Notes:
- API Consistency: We use pure modern Odoo API (no
cr/uidparameters,self.envinstead ofpool) to avoid conflicts. - Preserve Original Flow: Calling
super()ensures we don't break the default "Create Bill" logic—we just add our commission value on top. - Cover All Scenarios: The code handles both cases: when an invoice already exists for the order, and when you're creating a brand new one.
内容的提问来源于stack exchange,提问作者myriam

