Pular para o conteúdo
Odoo Menu
  • Entrar
  • Experimente grátis
  • Aplicativos
    Finanças
    • Financeiro
    • Faturamento
    • Despesas
    • Planilhas (BI)
    • Documentos
    • Assinar Documentos
    Vendas
    • CRM
    • Vendas
    • PDV Loja
    • PDV Restaurantes
    • Assinaturas
    • Locação
    Websites
    • Criador de Sites
    • e-Commerce
    • Blog
    • Fórum
    • Chat ao Vivo
    • e-Learning
    Cadeia de mantimentos
    • Inventário
    • Fabricação
    • PLM - Ciclo de Vida do Produto
    • Compras
    • Manutenção
    • Qualidade
    Recursos Humanos
    • Funcionários
    • Recrutamento
    • Folgas
    • Avaliações
    • Indicações
    • Frota
    Marketing
    • Redes Sociais
    • Marketing por E-mail
    • Marketing por SMS
    • Eventos
    • Automação de Marketing
    • Pesquisas
    Serviços
    • Projeto
    • Planilhas de Horas
    • Serviço de Campo
    • Central de Ajuda
    • Planejamento
    • Compromissos
    Produtividade
    • Mensagens
    • Aprovações
    • Internet das Coisas
    • VoIP
    • Conhecimento
    • WhatsApp
    Aplicativos de terceiros Odoo Studio Plataforma Odoo Cloud
  • Setores
    Varejo
    • Loja de livros
    • Loja de roupas
    • Loja de móveis
    • Mercearia
    • Loja de ferramentas
    • Loja de brinquedos
    Comida e hospitalidade
    • Bar e Pub
    • Restaurante
    • Fast Food
    • Hospedagem
    • Distribuidor de bebidas
    • Hotel
    Imóveis
    • Imobiliária
    • Escritório de arquitetura
    • Construção
    • Administração de propriedades
    • Jardinagem
    • Associação de proprietários de imóveis
    Consultoria
    • Escritório de Contabilidade
    • Parceiro Odoo
    • Agência de marketing
    • Escritório de advocacia
    • Aquisição de talentos
    • Auditoria e Certificação
    Fabricação
    • Têxtil
    • Metal
    • Móveis
    • Alimentação
    • Cervejaria
    • Presentes corporativos
    Saúde e Boa forma
    • Clube esportivo
    • Loja de óculos
    • Academia
    • Profissionais de bem-estar
    • Farmácia
    • Salão de cabeleireiro
    Comércio
    • Handyman
    • Hardware e Suporte de TI
    • Sistemas de energia solar
    • Sapataria
    • Serviços de limpeza
    • Serviços de climatização
    Outros
    • Organização sem fins lucrativos
    • Agência Ambiental
    • Aluguel de outdoors
    • Fotografia
    • Aluguel de bicicletas
    • Revendedor de software
    Navegar por todos os setores
  • Comunidade
    Aprenda
    • Tutoriais
    • Documentação
    • Certificações
    • Treinamento
    • Blog
    • Podcast
    Empodere a Educação
    • Programa de educação
    • Scale Up! Jogo de Negócios
    • Visite a Odoo
    Obtenha o Software
    • Baixar
    • Comparar edições
    • Releases
    Colaborar
    • Github
    • Fórum
    • Eventos
    • Traduções
    • Torne-se um parceiro
    • Serviços para parceiros
    • Cadastre seu escritório contábil
    Obtenha os serviços
    • Encontre um parceiro
    • Encontre um Contador
    • Conheça um consultor
    • Serviços de Implementação
    • Referências de Clientes
    • Suporte
    • Upgrades
    Github YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Faça uma demonstração
  • Preços
  • Ajuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Financeiro
  • Inventário
  • PoS
  • Projeto
  • MRP
All apps
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
Ajuda

One2many onchange in ODOO

Inscrever

Seja notificado quando houver atividade nesta publicação

Esta pergunta foi sinalizada
one2manyonchange
3 Respostas
14863 Visualizações
Avatar
sridhar

I having a form with one2many field, in that one2many it having 10 line items, in the form I update some sequence number to that one2many, if I change the value in 5th line item that sequences need to update 6th to 10th line item how to do that in ODOO.

@Axel Mendoza, In this image I change the value 6 as 15 then next records are need to change automatically. How to do that.

class xform(osv.osv):
 _name = 'xform'
 _columns = {
 'name': fields.char('Name', size=64),
 'xstate': fields.text('XState'),
 'xmany_ids': fields.one2many('xmany', 'xform_id', string='Xmany'),
 }
 _defaults = {
 'xstate': '{}'
 }
 def onchange_many_lines(self, cr, uid, ids, xmany_ids, xstate):
 #to save the state of modified fields to latter could detect new changes
 xstate = json.loads(xstate)
 lines = []
 xlast = False
 #for identify non saved lines
 index = 0
 for xline in xmany_ids:
 if not xlast:
 #detecting the actual modified line
 if xline[0] in (0,1) and xline[2].get('xvalue', False):
 if (xline[0] == 0 and xstate.get('new-%s'%index,False) != xline[2].get('xvalue')) or \
 (xline[0] == 1 and xstate.get(xline[1],False) != xline[2].get('xvalue')):
 xlast = xline[2].get('xvalue')
 if xline[0] == 0:
 xstate['new-%s'%index] = xline[2]
 if xline[0] == 1:
 xstate[xline[1]] = xline[2]
 lines.append(xline)
 print lines,"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
 else:
 #not a deleted line
 if xline[0] != 2:
 xlast+=1
 else:
 lines.append(xline)
 #new line not saved yet
 if xline[0] == 0:
 data = {'xvalue': xlast}
 if xline[2].get('name', False):
 data.update({'name': xline[2]['name']})
 lines.append((0, 0, data))
 xstate['new-%s'%index] = xlast
 #existing lines, 1: modified line and 4: linked line to an existing record
 elif xline[0] in (1,4):
 data = {'xvalue': xlast}
 if xline[0] == 1 and xline[2].get('name', False):
 data.update({'name': xline[2]['name']})
 lines.append((1, xline[1], data))
 xstate[xline[1]] = xlast
 index+=1
 if not xlast:
 print xlast,"PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP"
 return {}
 print json.dumps(xlast),"$$$$$$$$$$$$$$$$$$$$$$$$$$$"
 return {'values': {'xstate': json.dumps(xlast), 'xmany_ids': lines}}
xform()
class xmany(osv.osv):
 _name = 'xmany'
 _columns = {
 'name': fields.char('Name', size=64),
 'xvalue': fields.integer('XValue'),
 'xform_id': fields.many2one('xform', string='XForm'),
 }
xmany()
1
a
2
b
3
c
4
d
5
e
15
f
16
g
17
h
18
i
19
j
-2
Avatar
Cancelar
Axel Mendoza

Describe more what you need, it can be done but you need to be more specific

Avatar
Axel Mendoza
Melhor resposta

It's something tricky what you need. Here is an example that should solve your problem. It's developed in old Odoo API style. Enjoy it, maybe it's not exactly what you need or need a minor tweaks or validation but it's pretty complete

The models for the example:

from openerp.osv import fields, osv
import json

from openerp import api
from openerp.models import onchange_v7


class xform(osv.osv):
_name = 'xform'
_columns = {
'name': fields.char('Name', size=64),
'xstate': fields.text('XState'),
'xmany_ids': fields.one2many('xmany', 'xform_id', string='Xmany'),
}
_defaults = {
'xstate': '{}'
}

def update_state(self, xform):
xstate = {}
for line in xform.xmany_ids:
xstate[line.id] = line.xvalue
osv.osv.write(xform, {'xstate': json.dumps(xstate)})

@api.model
@api.returns('self', lambda value:value.id)
def create(self, vals):
xform = osv.osv.create(self, vals)
self.update_state(xform)
return xform

@api.multi
def write(self, vals):
res = osv.osv.write(self, vals)
self.update_state(self)
return res

def onchange_many_lines(self, cr, uid, ids, xmany_ids, xstate, **kwargs):
#to save the state of modified fields to latter could detect new changes
xstate = json.loads(xstate)
lines = []
xlast = False
#for identify non saved lines
index = 0

for xline in xmany_ids:
if not xlast:
#detecting the actual modified line
if xline[0] in (0,1) and xline[2].get('xvalue', False):
if (xline[0] == 0 and xstate.get('new-%s'%index,False) != xline[2].get('xvalue')) or \
(xline[0] == 1 and xstate.get(str(xline[1]),False) != xline[2].get('xvalue')):
xlast = xline[2].get('xvalue')
if xline[0] == 0:
xstate['new-%s'%index] = xline[2]['xvalue']
if xline[0] == 1:
xstate[str(xline[1])] = xline[2]['xvalue']
lines.append(xline)
else:
#not a deleted line
if xline[0] != 2:
xlast+=1
else:
lines.append(xline)
#new line not saved yet
if xline[0] == 0:
data = {'xvalue': xlast}
if xline[2].get('name', False):
data.update({'name': xline[2]['name']})
lines.append((0, 0, data))
xstate['new-%s'%index] = xlast
#existing lines, 1: modified line and 4: linked line to an existing record
elif xline[0] in (1,4):
data = {'xvalue': xlast}
if xline[0] == 1 and xline[2].get('name', False):
data.update({'name': xline[2]['name']})
lines.append((1, xline[1], data))
xstate[str(xline[1])] = xlast
index+=1
if not xlast:
return {}
return {'value': {'xstate': json.dumps(xstate), 'xmany_ids': lines}}

@api.multi
def onchange(self, values, field_name, field_onchange):
match = onchange_v7.match(field_onchange[field_name])
if match:
method, params = match.groups()

# evaluate params -> tuple
global_vars = {'context': self._context, 'uid': self._uid}
if self._context.get('field_parent'):
class RawRecord(object):
def __init__(self, record):
self._record = record
def __getattr__(self, name):
field = self._record._fields[name]
value = self._record[name]
return field.convert_to_onchange(value)
record = self[self._context['field_parent']]
global_vars['parent'] = RawRecord(record)
params = eval("[%s]" % params, global_vars, values)

# call onchange method with context when possible
args = (self._cr, self._uid, self._ids) + tuple(params)

try:
method_res = getattr(self._model, method)(*args, context=self._context)
except TypeError:
method_res = getattr(self._model, method)(*args)

return method_res
super(xform,self).onchange(values, field_name, field_onchange)

xform()

class xmany(osv.osv):
_name = 'xmany'
_columns = {
'name': fields.char('Name', size=64),
'xvalue': fields.integer('XValue'),
'xform_id': fields.many2one('xform', string='XForm'),
}
xmany()

in the view for the model xform:

        <record model="ir.ui.view" id="solt_xform_form_view">
<field name="name">xform</field>
<field name="model">xform</field>
<field name="arch" type="xml">
<form string="XFORM">
<field name="name"/>
<field name="xstate" invisible="1"/>
<field name="xmany_ids" on_change="onchange_many_lines(xmany_ids, xstate)">
<tree editable="bottom">
<field name="xvalue"/>
<field name="name"/>
</tree>
</field>
</form>
</field>
</record>

<record id="solt_xform_action" model="ir.actions.act_window">
<field name="name">XFORM</field>
<field name="res_model">xform</field>
<field name="view_type">form</field>
<field name="view_mode">tree,form</field>
</record>

<menuitem name="Many Tests" id="solt_many_menu" parent="base.menu_administration" sequence="5"/>
<menuitem name="XFORM" id="solt_xform_submenu" parent="solt_many_menu" action="solt_xform_action" sequence="3"/>

 

4
Avatar
Cancelar
Axel Mendoza

Change for xlast+=1

sridhar
Autor

This concept is not working in ODOO, but it is working in OpenERP 7.

Axel Mendoza

It should work with a few tweaks, Odoo doesn't change too much in that features and I have done already some codes like that way in Odoo v8

Axel Mendoza

I give you a very hard to guess way of solve your problem, creating the models to show you and example you need to adapt to what you need. I think at least a +1 vote it may deserve, try to understand the algorithm used with the tuple format, I left some comments in the code and If you don't get something you could always ask

sridhar
Autor

json.dumps(xlast), here it get False only.

Axel Mendoza

I fix the final json.dumps(xstate) because former I code wrong as xtate

sridhar
Autor

If I editing xvalue means json.dumps(xstate) is False only.

Axel Mendoza

If you edit xvalue in a line, there is a loop that detect the change in that line. xstate keep the values of all the xvalue lines for be able to detect other changes latter

sridhar
Autor

If i edit the lines means, i print the value lines.append(xline) but I got this values only, [(6, 0, [7, 8, 9, 10])],

Axel Mendoza

If you see (6,0,[ids]) then you are dealing with a many2many field or a one2many with a widget many2many in the view

sridhar
Autor

No, I'm using your code only, I didn't add any many2many widget in the view.

Axel Mendoza

let me try all latter, come back tomorrow for a solution, the code I give you was not tested at all, but it's simply to add [(6,0,[ids])] support

sridhar
Autor

Ok Thank you so much.

sridhar
Autor

@Axel Mendoza, Any update to this concept.

Axel Mendoza

I updated the code, it's working in all the scenarios. Please test it and comment if works for you

Está gostando da discussão? Não fique apenas lendo, participe!

Crie uma conta hoje mesmo para aproveitar os recursos exclusivos e interagir com nossa incrível comunidade!

Inscreva-se
Publicações relacionadas Respostas Visualizações Atividade
How to update two levels o2m fileds relation
one2many onchange
Avatar
0
set. 20
3686
Several levels of One2many
one2many onchange
Avatar
0
abr. 16
3816
How to Import one2many field record from one model to one2many field in another model
one2many onchange
Avatar
Avatar
1
mar. 15
13234
How to return domain on one2many field so that seleted values are not shown in next line
domain one2many onchange
Avatar
1
abr. 23
5908
onchange return domain for one2many product ID Field Resolvido
domain one2many onchange
Avatar
Avatar
Avatar
Avatar
7
abr. 23
19871
Comunidade
  • Tutoriais
  • Documentação
  • Fórum
Open Source
  • Baixar
  • Github
  • Runbot
  • Traduções
Serviços
  • Odoo.sh Hosting
  • Suporte
  • Upgrade
  • Desenvolvimentos personalizados
  • Educação
  • Encontre um Contador
  • Encontre um parceiro
  • Torne-se um parceiro
Sobre nós
  • Nossa empresa
  • Ativos da marca
  • Contato
  • Empregos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidade
  • Segurança
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo é um conjunto de aplicativos de negócios em código aberto que cobre todas as necessidades de sua empresa: CRM, comércio eletrônico, contabilidade, estoque, ponto de venda, gerenciamento de projetos, etc.

A proposta de valor exclusiva Odoo é ser, ao mesmo tempo, muito fácil de usar e totalmente integrado.

Site feito com

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now