odoo fields_view_get创建动态视图方法


odoo  fields_view_get方法是一个比较有用比较灵活的广泛,如果使用得当,可以做到一些常规方法无法实现的功能,本文列举若干种用法。

openerp的视图结构是以XML的格式存放于ir.ui.view表中,属于静态格式,设计之后就固定,

但可以通过在model中重写fields_view_get函数,在视图加载时修改arch属性,动态修改视图的结构

Odoo 开发中经常会遇到这样的需求,对象中根据条件是否显示一个字段。比如如果不是创建人,不不显示客户的联系方式,Odoo 中如何实现呢?<一>domain在 odoo 中可以根据对象字段的值或者关系确定是否显示一个字段。

动态 domain 的例子,根据选择结构确定字段是否显示。还有一种方式是,可以在 view 中,根据 states 的值确定字段是否显示。

view 的state

动态视图

用法一、 修改field的属性:

    def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
#override of fields_view_get in order to replace the name field to product template
if context is None:
context={}
res = super(product_product, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
#check the current user in group_product_variant
group_id = self.pool['ir.model.data'].get_object_reference(cr, uid, 'product', 'group_product_variant')[1]
obj = self.pool.get('res.groups').browse(cr, uid, group_id, context=context)
doc = etree.XML(res['arch'])
if view_type == 'form':
if obj and uid in [x.id for x in obj.users]:
for node in doc.xpath("//field[@name='name']"):
node.set('invisible', '1')
node.set('required', '0')
setup_modifiers(node, res['fields']['name']) #这行必须要有
for node in doc.xpath("//label[@string='Product Name']"):
node.set('string','Product Template')
else:
for node in doc.xpath("//field[@name='product_tmpl_id']"):
node.set('required','0')
setup_modifiers(node, res['fields']['product_tmpl_id']) #这行必须要有
for node in doc.xpath("//field[@name='name']"):
node.set('invisible', '0')
setup_modifiers(node, res['fields']['name']) #这行必须要有
for node in doc.xpath("//label[@string='Product Template']"):
node.set('string','Product Name')
res['arch'] = etree.tostring(doc)
return res

1

def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
if context is None:context = {}
res = super(rhwl_gene, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar,submenu=False)
if res['type']=="form":
id = res['id']
//根据id去取得资料,并进行判断
if 条件成立:
doc = etree.XML(res['arch'])
doc.xpath("//form")[0].set("edit","false")
res['arch']=etree.tostring(doc)
return res

2

def fields_view_get(self, cr, uid, view_id=None,view_type='form',context=None,toolbar=False,submenu=False):
ip_obj = self.pool.get('hr.rule.input')
res = super(hr_inputs_editor,self).fields_view_get(cr,uid,view_id,view_type,context,toolbar,submenu)
if view_type=='form':
treev = res['fields']['line_ids']['views']['tree']
doc = etree.XML(treev['arch'])
for node in doc.xpath("/tree/field"):
name = node.get('name',False)
if name.startswith('value'):
name = name.replace('value','input') + '_code'
cd = context.has_key(name) and context[name] or False
if cd:
ip_ids = ip_obj.search(cr,uid,[('code','=',cd)],limit=1,context=context)
if ip_ids:
text = ip_obj.read(cr,uid,ip_ids,['name'])[0]['name']
node.set('string',text)
else:
node.set('modifiers','{"tree_invisible":true}')
treev['arch'] = etree.tostring(doc)
return res

用法二、根据条件限制view是否可编辑(网上曾经有个人提出在指定日期内可以编辑,也可以参考下面的代码实现)

@api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
if view_type == 'form':
res['arch'] = self.fields_view_get_address(res['arch'])
record = self.env['crm.lead'].browse(self._context.get('params').get('id'))
# restrict modification and deletion of child ids
if record.parent_id:
res['arch'] = res['arch'][:6] + 'edit="false" delete="false" ' + res['arch'][6:]
elif record.stage_id.id == 4: # restrict edition of Purchased Lead
res['arch'] = res['arch'][:6] + 'edit="false" ' + res['arch'][6:]
return res

用法三、给视图动态增加field,下面的代码是给某视图动态增加一个field (product_id):

@api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
doc = etree.XML(res['arch'])
summary = doc.xpath("//field[@name='product_id']")
if len(summary):
summary = summary[0]
summary.addnext(etree.Element('field', {'name': 'product_id',
'string':'title of new field',
'nolabel':'0',
}))
res['arch'] = etree.tostring(eview)
return res

用法四、给视图增加一个page(跟用法三有些类似):

class product_product(osv.osv):
_inherit = 'product.product' def fields_view_get(self, view_id=None, view_type='form', toolbar=False,submenu=False):
"""
Changes the view dynamically
@param self: The object pointer.
@return: New arch of view.
"""
ret_val = super(product_product, self).fields_view_get(view_id, view_type, toolbar,submenu)
if view_type == 'form':
doc = etree.XML(ret_val['arch'], parser=None, base_url=None) #要加入到视图里的page
_moves_arch_lst = """
<page string='Feature'>
</page>
"""
first_node = doc.xpath("//page[@string='Sales']")
if first_node and len(first_node)>0:
#先把_moves_arch_lst转成XML Node,然后加到查找到node中
feature_page = etree.XML(_moves_arch_lst)
first_node.addnext(feature_page)
ret_val['arch'] = etree.tostring(doc, encoding="utf-8")
return ret_val

动态修改field的domain:

class account_voucher(osv.osv):
_inherit = 'account.voucher'
def fields_view_get(self, view_id=None, view_type=False, toolbar=False, submenu=False):
"""
Add domain 'allow_check_writting = True' on journal_id field
and remove 'widget = selection' on the same field
because the dynamic domain is not allowed on such widget
"""
if not context: context = {}
res = super(account_voucher, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
doc = etree.XML(res['arch'])
nodes = doc.xpath("//field[@name='journal_id']") # 检查context是否有指定的标志(write_check)
if context.get('write_check', False) :
for node in nodes: # 动态修改 journal_id 这个field的domain
node.set('domain', "[('type', '=', 'bank'), ('allow_check_writing','=',True),('your_field','=','value')]") # 把 widget 清空,原因在上面已经说了
node.set('widget', '') res['arch'] = etree.tostring(doc)
return res 原文链接: http://www.odoogo.com/post/87/#comment-block

odoo fields_view_get的更多相关文章

  1. (05)odoo数据库和业务操作

    以一个例子开头* To-do 向导   # 配置文件       __openerp_.py:         { 'name': 'To-do Tasks Management Assistant' ...

  2. (03)odoo模型/记录集/公用操作

    -----------------更新时间11:17 2016-09-18 星期日11:00 2016-03-13 星期日09:10 2016-03-03 星期四11:46 2016-02-25 星期 ...

  3. Odoo 12 开发手册指南(八)—— 业务逻辑 – 业务流程的支持

    在前面的文章中,我们学习了模型层.如何创建应用数据结构以及如何使用 ORM API 来存储查看数据.本文中我们将利用前面所学的模型和记录集知识实现应用中常用的业务逻辑模式. 本文的主要内容有: 以文件 ...

  4. Odoo : ORM API

    记录集 model的数据是通过数据集合的形式来使用的,定义在model里的函数执行时它们的self变量也是一个数据集合 class AModel(models.Model): _name = 'a.m ...

  5. odoo开发基础--模型之基本字段类型

    定义模型的时候,和python的其他框架类似,可以对比Django,同样是一个模型即:一个class对应生成数据库中的一张表, 只是odoo的继承机制比较复杂一点,在日常的开发中,定义模型的时候, 基 ...

  6. Odoo 11 Backend

    Table of Contents 命令入口 服务器 启动server thread 模式 prefork 模式 gevent模式 wsgi 应用 响应 客户端请求 xmlrpc web http路由 ...

  7. odoo action

    动作的加载: 刷新视图页面执行load_views方法 /web/dataset/call_kw/model_name/load_views 在odoo/models.py的BaseModel中有一个 ...

  8. Odoo中的五种Action详解

    转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/10826232.html Odoo中的五种action都是继承自ir.actions.actions模型实现的 ...

  9. odoo controller 继承

    方式一: 继承基类,直接重写方法 from odoo.addons.web.controllers.main import Export class PsExport(Export): @http.r ...

随机推荐

  1. FineUIPro v6.0.1 小版本更新!

    这次修正了 v6.0.0版本的几个问题,建议所有用户升级到此版本: +修正调用F.addMainTab时可能出现JS错误的问题(34484135,1450561644).    -仅在未调用F.ini ...

  2. 深入理解Java8中Stream的实现原理

    Stream Pipelines 前面我们已经学会如何使用Stream API,用起来真的很爽,但简洁的方法下面似乎隐藏着无尽的秘密,如此强大的API是如何实现的呢?比如Pipeline是怎么执行的, ...

  3. npm install说明

    一.常用简写 npm install=npm i.在git clone项目的时候,项目文件中并没有 node_modules文件夹,项目的依赖文件可能很大.直接执行,npm会根据package.jso ...

  4. Flask-Moment本地化日期和时间

    moment.js客户端开源代码库,可以在浏览器中渲染日期和时间.Flask-Moment是一个flask程序扩展,能把moment.js集成到Jinja2模板中. 1.安装 pip install ...

  5. 【Zabbix】zabora监控Oracle数据库

    zabora监控Oracle数据库 它作为一个开源项目,通过shell脚本有效的监控Oracle基础指标.本文档旨在通过实战,在Zabbix 3.0版本之下,监控生产环境下的多台Oracle数据库. ...

  6. SimdJsonSharp:每秒解析千兆字节的JSON

    SimdJsonSharp: Parsing gigabytes of JSON per second C# version of lemire/simdjson (by Daniel Lemire ...

  7. C# 中如何深度复制某一个类型(备注:可能有 N 个类型需要复制)的对象?

    如题,针对某一个特定的类型,深度复制,没有那么难,最起码可以手动赋值,但如果要针对 N 多类型深度复制,最简单的方法,是把这个对象序列化成 XML.JSON 或其它可以序列化的载体,然后再将这个载体反 ...

  8. Linux SELinux 介绍详解

    Linux SELinux 介绍详解 SElinux 简介 SElinux (Security Enhanced Linux)是由美国国家安全局(NSA)开发的.它已被植入到了Linux系统的内核当中 ...

  9. 基于Vue + axios + WebApi + NPOI导出Excel文件

    一.前言 项目中前端采用的Element UI 框架, 远程数据请求,使用的是axios,后端接口框架采用的asp.net webapi,数据导出成Excel采用NPOI组件.其业务场景,主要是列表页 ...

  10. F#周报2019年第19期

    新闻 介绍.NET 5 发布.NET Core 3.0预览版5以及F#的REPL OpenFsharp CFP开启 F#的Giraffe服务端stub生成器被添加到openapi-generator中 ...