我们在开发odoo14的时候经常会遇到一个问题,就是你在templates写的布局,你想在form视图上显示。
这时候就需要用JS和xml交互来实现了
下面我就教你怎么做。
首先 我们正常写一个模型,里面有Form视图
然后在py文件里面随便写一个字段,
description = fields.Text(string='Description')
在form视图上面显示这个字段
<field name="description" nolabel="1" />
这会加载视图就可以看到这个字段
在static/src/xml/custom_template.xml
创建这么一个xml,因为这个里面主要是写我们的template
里面内容就随便写写
<templates xml:space="preserve">
<t t-name="custom_template">
<p>
123
</p>
</t>
</templates>
t-name="custom_template"
这句话是你的这个template 名字,等会通过它来找到这个template
然后在
__manifest__.py
文件里面引用你刚刚写的xml
'qweb': [
'static/src/xml/custom_template.xml',
],
在static/src/js/custon_widget.js 创建一个JS文件
里面代码如下
odoo.define('you_model.custom_widget', function (require) {
'use strict';
const registry = require('web.field_registry');
var core = require('web.core');
var QWeb = core.qweb;
var FieldText = require('web.basic_fields').FieldText;
var _t = core._t;
var CustomWidget = FieldText.extend({
/**
* @override
*/
_renderReadonly: function () {
this.$el.html(QWeb.render('custom_template', {record: this.record.data}));
},
});
registry.add('custom_widget', CustomWidget);
return CustomWidget;
});
this.$el.html(QWeb.render('custom_template', {record: this.record.data}));
这句话就是你获取到你当前模型里面的数据,然后到了template里面 你通过record来进行赋值
这个JS主要意思就是通过Q-web找到template,然后渲染到你想要的地方。
写完JS你需要找个地方引用这个JS
然后在views文件夹下创建一个xml
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<data>
<template id="st_inherit" inherit_id="web.assets_backend" name="Your Module Assets">
<xpath expr="." position="inside">
<script type="text/javascript" src="/goa_handover_record/static/src/js/custom_widget.js"></script>
<link rel="stylesheet" href="/goa_handover_record/static/src/scss/custom_style.css"/>
</xpath>
</template>
</data>
</odoo>
加载你的JS,我这里面还写了一个CSS样式,你如果不需要可以不写
在回到__manifest__.py
添加这个xml
'data': [
'views/js_setup_view.xml',
],
这时候 你回到你之前创建的template里面
<templates xml:space="preserve">
<t t-name="custom_template">
<div class="oe_mt32 table table-condensed">
<span t-esc="record.signed_by" />
<span t-esc="record.signed_on" />
</div>
</t>
</templates>
添加上面的内容,其中
<span t-esc="record.signed_by" />
<span t-esc="record.signed_on" />
这里面的signed_by和signed_on是我模型里面的两个字段,我把字段的值传到模型里面
当前 你看到这里会有疑问,你写了这么多也没有在你的Form视图上用啊!
这时候你回到你的Form视图 在加一句话
<field name="description" nolabel="1" widget="custom_widget" />
把刚刚的JS写成小组件传到Form视图上,这时候就可以把你在template里面的内容渲染到Form视图上