12. 动作与按钮
适用版本
Odoo 20 社区版 · 对应官方文档 Chapter 9(Ready for Some Action?)
第 12 课:动作与按钮
12.1 目标
上一节课中,我们完成了视图的学习,能看了房源的数据列表和房源的详细数据了,这节课中将为每一条房源信息新增几个业务动作(成交、取消、批量调价),同时解决下面三个问题:
- 按钮的写法有几种,
workflow还能不能用? - 弹窗式表单(向导)怎么做,选中的那几条记录怎么传进去?
- 状态流转要不要校验,不校验会出什么问题?
12.2 Odoo 的做法
12.2.1 按钮只有两种 type
| 写法 | name 写什么 | 用途 |
|---|---|---|
type="object" | 本模型的方法名 | 最常见的业务动作 |
type="action" | 动作的 xmlid 或 id(XML 数据里常写 %(xmlid)d,加载时替换成 id) | 打开另一个动作(如弹窗、报表) |
不写 type,写 special | — | special 只有 cancel / save / add 三个合法值 |
写了 special 就不再校验 type;反过来说,既不写 type、又没 special 的按钮,点击时前端直接抛 InvalidButtonParamsError: Missing type for doActionButton request。
workflow 不是"已废弃",是已经移除(Odoo 17 起就没有这套机制,源码里连分支都不剩)。它的坑在于很难查:视图校验会放过它(ir_ui_view._validate_tag_button 对非 object / action 的 type 直接 return),升级不报错,只有真点下去才炸。
list 的 <groupby> 行头、看板与 QWeb 模板里还能见到 type="edit"、type="delete" 这类按钮,由各自组件处理,不走这条通用链路,别当成第四种 type。
按钮的显隐靠 invisible 表达式(第 9 课讲过的字符串表达式),不写 states:
<button name="action_mark_sold" type="object" string="成交"
class="btn-primary" invisible="state != 'offer'"/>2
12.2.2 方法返回什么
对象按钮调用的方法,返回值决定前端下一步:
- 返回
None/False:留在原页面,只刷新(最常用); - 返回一个动作字典:前端执行它,比如
{'type': 'ir.actions.act_window_close'}关闭弹窗、{'type': 'ir.actions.client', 'tag': 'reload'}强制刷新。
按钮只能调公开方法:以 _ 开头的方法在视图里会被拒绝(20 对私有方法的限制更彻底),所以业务动作统一命名成 action_xxx。
type="object" 在视图校验阶段就会查方法名:写错报 xxx is not a valid action on estate.property,不用等到点按钮才发现;方法带必填参数只给一条警告,点了才会 TypeError。
12.2.3 服务端动作:不写视图也能加"动作菜单"
model="ir.actions.server" 是存在数据库里的动作,state=code 时可以写一段 Python(model、record、records、env 都在上下文里)。它的价值是给列表页加"动作"下拉菜单,不用改前端:
<record id="action_server_archive_expired" model="ir.actions.server">
<field name="name">归档长期未成交房源</field>
<field name="model_id" ref="model_estate_property"/>
<field name="binding_model_id" ref="model_estate_property"/>
<field name="binding_view_types">list</field>
<field name="state">code</field>
<field name="code">records.filtered(lambda r: r.state == 'new').write({'active': False})</field>
</record>2
3
4
5
6
7
8
12.2.4 向导:TransientModel
需要用户填几个参数再执行(比如"按百分比调价")时,用向导。它和普通模型几乎一样,区别是:
| 特性 | 普通模型 | TransientModel |
|---|---|---|
| 数据寿命 | 长期 | 临时,会被系统定期清理 |
| 打开方式 | 菜单/动作 | 动作里 target=new(弹窗) |
| 典型用途 | 业务数据 | 收集参数、确认操作 |
把"当前选中的记录"带进向导靠上下文:动作的 context 里写 default_xxx: [(6, 0, active_ids)],向导里就能拿到。
12.2.5 状态机:字段 + 按钮 + 校验,缺一不可
流程类的模型要有一个 state 字段,并把"合法流转"写在方法里:
if rec.state != 'offer':
raise UserError('只有"有意向"的房源可以标记成交')2
只用 invisible 藏按钮是不够的:按钮能藏,接口、导入、批量动作都藏不住。校验必须写在服务端方法里,视图只是体验层。
12.3 开发实践
12.3.1 加状态字段与业务方法
from odoo import fields, models
from odoo.exceptions import UserError
class EstateProperty(models.Model):
# ... 前面章节的字段
state = fields.Selection(
selection=[
('new', '新上架'),
('offer', '有意向'),
('sold', '已售出'),
('cancel', '已取消'),
],
string='状态', default='new', required=True, copy=False,
)
def action_mark_offer(self):
for rec in self:
if rec.state != 'new':
raise UserError('只有"新上架"的房源可以转为有意向。')
rec.state = 'offer'
def action_mark_sold(self):
for rec in self:
if rec.state != 'offer':
raise UserError('只有"有意向"的房源可以标记成交。')
if not rec.selling_price:
raise UserError('成交前请先填写成交价。')
rec.state = 'sold'
def action_cancel(self):
for rec in self:
if rec.state == 'sold':
raise UserError('已成交的房源不能取消。')
rec.state = 'cancel'2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
12.3.2 表单头部接上按钮
<form string="房源">
<header>
<button name="action_mark_offer" type="object" string="转为有意向"
class="btn-primary" invisible="state != 'new'"/>
<button name="action_mark_sold" type="object" string="成交"
class="btn-primary" invisible="state != 'offer'"/>
<button name="action_cancel" type="object" string="取消"
invisible="state in ('sold', 'cancel')"/>
<field name="state" widget="statusbar" statusbar_visible="new,offer,sold"/>
</header>
<sheet>
<!-- 原有内容 -->
</sheet>
</form>2
3
4
5
6
7
8
9
10
11
12
13
14
statusbar 只负责显示进度条,不负责拦截——拦截在方法里。
12.3.3 批量调价向导
models/estate_price_wizard.py:
from odoo import fields, models
class EstatePriceAdjustWizard(models.TransientModel):
_name = 'estate.price.adjust.wizard'
_description = '批量调整期望售价'
property_ids = fields.Many2many('estate.property', string='房源')
percent = fields.Float(string='调整幅度(%)', default=-5.0, required=True)
def action_apply(self):
for prop in self.property_ids:
prop.expected_price = prop.expected_price * (1 + self.percent / 100)
return {'type': 'ir.actions.act_window_close'}2
3
4
5
6
7
8
9
10
11
12
13
14
views/estate_price_wizard_views.xml:视图 + 动作(动作上绑定到列表,选中记录后从「动作」菜单进入):
<odoo>
<record id="view_estate_price_adjust_wizard_form" model="ir.ui.view">
<field name="name">estate.price.adjust.wizard.form</field>
<field name="model">estate.price.adjust.wizard</field>
<field name="arch" type="xml">
<form string="批量调整期望售价">
<group>
<field name="property_ids" widget="many2many_tags" readonly="1"/>
<field name="percent"/>
</group>
<footer>
<button name="action_apply" type="object" string="确定" class="btn-primary"/>
<button string="取消" class="btn-secondary" special="cancel"/>
</footer>
</form>
</field>
</record>
<record id="action_estate_price_adjust_wizard" model="ir.actions.act_window">
<field name="name">批量调整期望售价</field>
<field name="res_model">estate.price.adjust.wizard</field>
<field name="view_mode">form</field>
<field name="target">new</field>
<field name="binding_model_id" ref="model_estate_property"/>
<field name="binding_view_types">list</field>
<field name="context">{'default_property_ids': [(6, 0, active_ids)]}</field>
</record>
</odoo>2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
别忘了给向导模型配权限(TransientModel 也要):
access_estate_price_adjust_wizard,estate price adjust wizard,estate.price.adjust.wizard,estate20.group_estate_agent,crud,然后在列表页勾选几条房源 → 「动作」→「批量调整期望售价」,弹窗里改幅度、点确定。
12.3.4 验证
同上一章:跑之前确认 odoo.conf 的 addons_path 指向本章的模块目录(配套示例是 D:/workspace/winodoo/samples/ch12)。
cd D:\odoo20
venv\Scripts\activate
python odoo-bin -c odoo.conf -u estate20
python odoo-bin shell -c odoo.conf -d odoo20db2
3
4
Odoo shell 代码块:
from odoo.exceptions import UserError
rec = env['estate.property'].search([], limit=1)
rec.action_mark_offer(); rec.state # 'offer'
rec.action_mark_sold() # 未填成交价时抛 UserError
rec.selling_price = 600000
rec.action_mark_sold(); rec.state # 'sold'
try:
rec.action_cancel() # sold 状态禁止取消
except UserError as e:
print('UserError:', e) # 已成交的房源不能取消。
print(rec.state) # 'sold',没有变成 cancel
quit()2
3
4
5
6
7
8
9
10
11
12
13
14
15
两条命令确认动作确实落库(第一条查向导的窗口动作,第二条查它有没有绑到房源的「动作」菜单):
SELECT name ->> 'en_US', res_model, target FROM ir_act_window
WHERE res_model = 'estate.price.adjust.wizard';
SELECT name ->> 'en_US', binding_model_id, binding_view_types FROM ir_act_window
WHERE res_model = 'estate.price.adjust.wizard';2
3
4
target 是 new、binding_view_types 是 list、binding_model_id 指向 estate.property,才算配好。
12.2.3 讲的 ir.actions.server 只是写作示范,配套示例没有把它放进模块——想试就把那段 <record> 贴进视图文件再 -u,然后用 SELECT name ->> 'en_US', state FROM ir_act_server WHERE model_id = (SELECT id FROM ir_model WHERE model = 'estate.property'); 查。
交给 AI(第 12 章 · 按钮与向导)
把下面这段发给任意 AI 对话(ChatGPT / Claude / Cursor 均可):
我们用的是 Odoo 20 社区版。模型 estate.property 有 state(new/offer/sold/cancel)、selling_price、expected_price。
请生成:① 三个对象按钮方法(转有意向、成交、取消),每个都在服务端做状态校验并抛 UserError;② 表单 header 里三个按钮,用 invisible 表达式控制显隐,带 statusbar;③ 一个 TransientModel 批量调价向导 + 绑定到列表的动作,要求 target=new 且把选中记录带进 property_ids。给出权限 CSV 行。
12.4 总结
验收清单
- 新建房源状态为「新上架」,页面上只有"转为有意向"和"取消"两个按钮
- 手动改库把状态置为
offer后刷新,能点"成交";不填成交价点击抛UserError - shell 里对
sold状态的记录调action_cancel(),抛UserError而不是改成功 - 列表勾选多条 → 动作菜单里有「批量调整期望售价」,确定后价格按百分比变化
SELECT count(*) FROM ir_act_window WHERE target='new';大于 0
12.5 常见坑与排错
| 现象 | 原因 | 处理 |
|---|---|---|
| 点按钮报"方法不存在" | name 写错,或方法名以 _ 开头 | 用公开的 action_xxx 命名 |
| 按钮不显示 | invisible 表达式写反,或字段没在视图里 | 检查表达式,把 state 放进视图 |
| 弹窗打开是空表单 | 动作里 default_xxx 拼接的上下文没生效 | 确认 active_ids 存在、字段名拼写一致 |
| 向导点确定后窗口不关 | action_apply 没返回关闭动作 | 返回 {'type': 'ir.actions.act_window_close'} |
向导报 AccessError | TransientModel 没配权限 | 补 ir.access.csv |
| 通过导入/接口改了状态 | 校验只写在视图的 invisible 里 | 校验必须写进方法,视图只是体验 |
| 服务端动作执行后没刷新 | 动作只改了数据 | 代码里可 env['estate.property'].invalidate_model(),或让前端返回 reload |
参考与致谢:本章知识结构参考 Odoo 官方文档 Chapter 9: Ready for Some Action? (Odoo S.A.,CC BY-SA 4.0)。按钮类型对照、状态机校验写法、TransientModel 向导示例均为本站基于 Odoo 20 社区版独立编写并实测。 本站非 Odoo 官方站点,内容不代表 Odoo S.A. 观点。