如何在Odoo 17日历视图中显示树形/看板视图同款「新建」按钮?
问题
我正在使用Odoo 17,为自定义模型创建了日历视图。在树形视图和看板视图中,左上角会显示标准的「新建」按钮,供用户创建新记录。但在日历视图中,该按钮未显示。我已在日历视图定义中设置了create="true",且点击日历区域可正常快速创建记录。不过我希望日历视图的头部也能显示与其他视图一致的标准「新建」按钮,请问是否有办法启用或强制显示该按钮?
以下是我的视图代码片段:
<calendar string="Appointments" date_start="date" date_stop="date_to" mode="week" color="state" create="true" event_open_popup="true" quick_create="true" quick_create_view_id="%(view_dental_appointment_quick_create)d"> <field name="name"/> <field name="patient_id"/> <field name="physician_id"/> <field name="department_id"/> <field name="duration_id"/> <field name="phone"/> <field name="cabin_id"/> <field name="state"/> </calendar>
解决方案
Odoo 17的日历视图默认不会渲染顶部的「新建」按钮,即使设置了create="true",你可以通过以下两种方式解决:
方法1:通过视图扩展添加按钮
在你的模块中创建视图扩展,为日历视图头部添加「新建」按钮:
<record id="view_dental_appointment_calendar_inherit" model="ir.ui.view"> <field name="name">dental.appointment.calendar.inherit</field> <field name="model">dental.appointment</field> <!-- 替换为你的自定义模型名 --> <field name="inherit_id" ref="你的日历视图ID"/> <!-- 替换为原日历视图的ID --> <field name="arch" type="xml"> <xpath expr="//calendar" position="before"> <header> <button name="action_new" type="object" string="新建" class="btn-primary"/> </header> </xpath> </field> </record>
该按钮会调用模型默认的action_new方法,打开新建表单视图;如果你的模型有自定义新建逻辑,可替换为自己的方法。
方法2:全局修改日历控制器模板
如果需要让所有日历视图都显示顶部「新建」按钮,可以继承Odoo的日历控制器模板:
odoo.define('your_module.calendar_controller', function (require) { "use strict"; const CalendarController = require('web.CalendarController'); const viewRegistry = require('web.view_registry'); const CustomCalendarController = CalendarController.extend({ renderButtons: function () { this._super.apply(this, arguments); if (this.renderer.state.isCreateEnabled) { const $newButton = $('<button>', { class: 'btn btn-primary o_list_button_add', text: '新建' }).on('click', () => { this.action.doAction({ type: 'ir.actions.act_window', res_model: this.modelName, views: [[false, 'form']], target: 'current', flags: {form: {action_buttons: true, mode: 'edit'}} }); }); this.$buttons.prepend($newButton); } } }); viewRegistry.add('calendar', CustomCalendarController); return CustomCalendarController; });
然后在模块的__manifest__.py中声明该JS文件:
'data': [ # ... 其他视图/数据文件 ], 'assets': { 'web.assets_backend': [ 'your_module/static/src/js/calendar_controller.js', ], },
内容的提问来源于stack exchange,提问作者Lochinbek Abdiyev
相关产品推荐
相关产品推荐

