如何添加按钮或 link 以重定向到树视图 odoo 12 内的另一个模型?

How to add a button or a link to re-direct to another model inside a tree view odoo 12?

我尝试在 XML 中提供小部件 ='url', 实际上我想做的是,我有一个名为 A 和 B 的模型,A 与 B 的关系为 One2many。所以我想从模型 A 的树视图加载到模型 B。(就像从表单视图单击按钮时它加载模型 B,我可以从树视图实现吗?

class test(models.Model):
    _name = 'consultation'

    test_id = fields.One2many('case.sheet','consultation_id',string='Case Sheet Id')

您可以通过一个按钮和一个动作来完成。首先,您需要在树视图中添加一个按钮:

<button type="object" name="go_to_model_B" string="To Model B" icon="fa-search"/>

这里的 name 道具是模型 A 中的一个方法(icon 道具是可选的,但我认为它看起来更好)。该方法是这样的:


# Method in Model A
def go_to_model_B(self):
    name_form = _('FORM B')
    return {
        'name': NAME_FORM,
        'type': 'ir.actions.act_window',
        'view_type': 'form',
        'view_mode': 'form',
        'res_model': 'MODEL.B',
        'res_id': self.consultation_id.id,  # Reference to the other model
        'target': 'new',
        'view_id': self.env.ref(
            'FORM_VIEW_MODEL_B').id,
        'context': {} # Optional
    }

也许您想在新标签页中打开表单,这是另一个选项:

import werkzeug.utils

def go_to_model_B(self):
    url_base = "{}/web?&#id={}&view_type=form&model={}&action={}'"
    action = "MODULE.ACTION_FORM_MODEL_B" # Name of the action defined in some XML
    model_name = "MODEL.B"
    target_record_id = self.consultation_id.id
    url = url_base.format(domain, target_record_id, model_name, action)
    return werkzeug.utils.redirect(url)

另一种方法是使用 ir.actions.act_url:

 def go_to_model_B(self):
    return {
        'name': "TO MODEL B"
        'type': 'ir.actions.act_url',
        'url': url,  # The url is the same as above
        'target': 'new'
    }

当您在树视图中点击一行时,Odoo 将加载 default 表单视图以显示相应的行记录。

url 小部件使用字段值作为 href 属性的值(如果我们不指定 text 属性,它将使用字段值)。

button 元素可以是 list view 的子元素并显示不同于树视图中使用的自定义表单视图,您可以在test_id 字段的树视图并在 case.sheet.

中声明一个具有相同名称的方法

示例:

case.sheet模型中声明方法:

class CaseSheet(models.Model):
    _name = 'case.sheet'

    @api.multi
    def open_form_view(self):
        self.ensure_one()
        form_view = self.env.ref('MODULE.XML_VIEW_ID')
        return {
            'name': _('Case sheet'),
            'res_model': 'case.sheet',
            'res_id': self.id,
            'views': [(form_view.id, 'form'), ],
            'type': 'ir.actions.act_window',
            'target': 'new',
        }

将按钮添加到树视图:

<field name="test_id">
    <tree editable="bottom">
        <field name="name"/>
        <button name="open_form_view" type="object" string="View" class="oe_highlight"/>
    </tree>
</field>