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

How to use same field more than once in a form?

Inscrever

Seja notificado quando houver atividade nesta publicação

Esta pergunta foi sinalizada
moduleviewwidgetfield
3 Respostas
24882 Visualizações
Avatar
thenon

What would the view xml look like for a module that needed to use the same field more than once?

Explanatory example: you want to allow a phone number to be editable (like normal),

< field name="phone" />

but also want to do something like:

< field name="phone" widget="web_skypeButton" />

elsewhere on the page.

Whenever I include both, neither gets the value. Is there a better way of doing this?

2
Avatar
Cancelar
thenon
Autor

A related field from the object to itself?

Avatar
Francesco OpenCode
Melhor resposta

You must use a function field for this:

class your_class(osv.osv):

    _inherit = "your.class"

    def _your_function(self, cr, uid, ids, name, arg, context=None):
        res = {}
        for id in ids:
            record = self.browse(cr, uid, id)
            res.update({id:record.phone})
        return res

    _columns = {
        'your_field' : fields.function(_your_function, type='char', size=32, method=True, store=False, multi=False),
        }

your_class()

and this is your view:

<record id="your_view" model="ir.ui.view">
            <field name="name">your.view.form</field>
            <field name="model">your.class</field>
            <field name="inherit_id" ref="original_module.original_form_view"/>
            <field name="arch" type="xml">
                <field name="phone" position="after">
                        <field name="your_field"/>
                </field>
            </field>
        </record>
5
Avatar
Cancelar
thenon
Autor
  Thanks for that.   By record.phone I assume you meant record.your_field?

If so, I'm still confused by what the view would look like. This doesn't work for example:

   &lt;field name="arch" type="xml"&gt;
            &lt;field name="email" position="after"&gt;
                &lt;field name="your_field" string="Short code"/&gt;
            &lt;/field&gt;

            &lt;field name="your_field" position="after"&gt;
                &lt;field name="_your_function" string="Short code2"/&gt;
            &lt;/field&gt;
  &lt;/field&gt;


  and neither does:
thenon
Autor
         &lt;field name="arch" type="xml"&gt;
            &lt;field name="email" position="after"&gt;
                &lt;field name="your_field" string="Short code"/&gt;
                &lt;field name="_your_function" string="Short code2"/&gt;
            &lt;/field&gt;
  &lt;/field&gt;
Francesco OpenCode

I edit the answer with right situation

thenon
Autor

Thanks Francesco, but that view only contains one instance of the field, not two?

Francesco OpenCode

two. Phone is the original field and Your_Field is the second instance

thenon
Autor

In my instance phone is NOT already on the view - I'm trying to display two fields - one as normal edit, one as a widget (see my sample code) . I used phone as an easy to understand example to demonstrate the use case, but I need to declare both. The first field is actually the edit field. The second is going to be rendered by a widget and display something different with that field.

Francesco OpenCode

I'm sorry but I can't explain in 500 charaters how to create a view for openerp module. All you need to know is that with the field function you can duplicate your original field content. I do assume that you already know how to create a view for an openerp module.

thenon
Autor

Perhaps you could advise if this code is correct? http://pastebin.com/5TJx3d55

Francesco OpenCode

line 14 must be: res.update({id:record.mycol})

thenon
Autor

That code is not quite correct (should be record.mycol) - but now have it working essentially in that both are being rendered ! Thank you. Now just need to work out how to include a xpath AND a normal "after" field at the same time...

thenon
Autor

And the answer for anyone else looking, is to wrap in a <data> element.

Avatar
Ray Carnes
Melhor resposta

I think you probably need a related field. Every time I've seen people put the same field on a form more than once, things don't work properly.

It much easier and probably faster than using functional fields as other answers suggested.

    _columns = {
        'phone': fields.integer('Phone'),
        'phone_2': fields.related('phone', string='Phone'),
    }

3
Avatar
Cancelar
Avatar
Vasiliy Birukov
Melhor resposta

You can define two field:

  • first - what you need
  • second - functional field, that return value from first field

This code for python:

class phone_example(osv.osv):
    _name = 'phone.example'

    def _get_phone(self, cr, uid, ids, name, arg, context=None):
        res = {}
        for phone in self.browse(cr, uid, ids, context=context):
            res[phone.id] = phone.phone
        return res

    _columns = {
        'phone': fields.integer('Phone'),
        'phone_2': fields.function(_get_phone, method=True),
    }

Then you can use two field, that will show the same.

Note. Second field will show only data from DB. If you change first in form, second don't update while you don't save form. Use also onchange method for update second field realtime.

2
Avatar
Cancelar
thenon
Autor

I'm very new to python - what would that second one look like in code please?

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
What are the available widgets in v7?
view widget field v7
Avatar
Avatar
1
mar. 15
5059
How to add widget to boolean field??
widget field odoo
Avatar
Avatar
1
mar. 25
8128
How to show datetime field as "xx days ago"
view field datetime
Avatar
0
mar. 21
3695
How to show a symbol inside a field like with the monetary widget? Resolvido
widget field monetary
Avatar
Avatar
1
mai. 17
5274
how to customize year range in date field? Resolvido
date widget field
Avatar
Avatar
1
ago. 15
6197
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