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

A custom form widget causes weird undesirable side effects

Inscrever

Seja notificado quando houver atividade nesta publicação

Esta pergunta foi sinalizada
clientwidget
6644 Visualizações
Avatar
Marvin Taboada

Hi, I have a fair simple example that uses a custom form widget, written previously using on_chage methods, that causes its form view to behave erratically. I'm using OpenERP 7.0, and object/view inheritance in a custom HR module.

Below are some brief details about the related requirement and the undesirable side effects that I would like to get rid of in my current implementation.

Requirement: The original HR module stores employee names in a single 'name' field ('name' is actually defined at 'resource.resource' and 'hr.employee' reuses it with delegation inheritance). We require to split the name into three fields, 'firstname' (required), 'middlename' (optional) and 'lastname' (required). At creation, an employee requires only 'firstname' and 'lastname', and 'name' should be hidden and should be automatically derived by concatenating the name-parts.

1st Solution - Server Side Based: Our first solution was to (1) hide the 'name' field in the form, (2) add the new three fields, and (3) define a single on_change method that concatenates the name-parts and fills the hidden 'name' field. This solution works well, but we want to move this logic completely to the client side to reduce the requests to the server, so it is currently discarded.

2nd Solution - Client Side Based: Based in the first first solution, (1) remove the on_change method and (2) use a custom form widget to listen changes in any of the name-parts, concatenate them and store the result in the 'name' field, directly in the client side. This solution partially works, name-parts are correctly concatenated at creating employees, but now the employee form does not correctly reset fields after employee edit/view, it renders dirty forms at attempting to create new employees (name-parts pre-populated with stale values) and renders inaccurate information at viewing records details in read mode. Only by navigating with the left/right arrows we are able to see accurate information. We used the following link as reference: https://doc.odoo.com/trunk/training/components/#the-form-view-custom-widgets

As I cannot attach the zipped module, below I'm adding the essential model/view/js sources of my module:

Model:

# -*- coding: utf-8 -*-

from openerp.osv import osv
from openerp.osv import fields

class hr_employee(osv.Model):
    """Customizations for 'hr.employee'."""
    _name = 'hr.employee'
    _inherit = 'hr.employee'

    def init(self, cursor):
        # New required fields: Update DB schema and data only when required
        cursor.execute('SELECT id FROM hr_employee '
                       'WHERE firstname IS NULL OR lastname IS NULL LIMIT 1')
        if cursor.fetchone():
            # Update required fields consistently
            cursor.execute('UPDATE hr_employee SET firstname = \'\' '
                           'WHERE firstname IS NULL')
            cursor.execute('UPDATE hr_employee SET lastname = name_related '
                           'WHERE lastname IS NULL')
            # Create SQL constraints, table is not empty
            cursor.execute('ALTER TABLE hr_employee '
                           'ALTER COLUMN firstname SET NOT NULL')
            cursor.execute('ALTER TABLE hr_employee '
                           'ALTER COLUMN lastname SET NOT NULL')

    _columns = {
        'firstname': fields.char("First Name", size=80, required=True),
        'middlename': fields.char("Middle Name", size=80),
        'lastname': fields.char("Last Name", size=80, required=True),
    }

hr_employee()

View:

<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data>
        <record model="ir.ui.view" id="view_extended_employee_form">
            <field name="name">hr.employee.form.inherit</field>
            <field name="model">hr.employee</field>
            <field name="inherit_id" ref="hr.view_employee_form"/>
            <field name="priority" eval="20"/>
            <field name="arch" type="xml">
                <data>
                    <label for="name" class="oe_edit_only" position="replace"/>
                    <field name="name" position="replace">
                        <field name="name" invisible="True"/>
                    </field>
                    <label for="category_ids" position="before">
                        <label for="firstname"/>
                        <field name="firstname"/>
                        <label for="middlename"/>
                        <field name="middlename"/>
                        <label for="lastname"/>
                        <field name="lastname"/>
                        <widget type="concat_name_parts"/>
                    </label>
                </data>
            </field>
        </record>
    </data>
</openerp>

JavaScript (widgets):

openerp.hr_extra = function(openerp) {
    /*
     * Custom widget to concatenate first, middle and last names. Usage:
     * <widget type="concat_name_parts"/>
     */
    openerp.hr_extra.WidgetConCatCompleteName = openerp.web.form.FormWidget.extend({
        start : function() {
            this._super();
            this.field_manager.on("field_changed:firstname", this, this.concat_name_parts);
            this.field_manager.on("field_changed:middlename", this, this.concat_name_parts);
            this.field_manager.on("field_changed:lastname", this, this.concat_name_parts);
            this.concat_name_parts();
        },
        concat_name_parts : function() {
            var firstname = this.field_manager.get_field_value("firstname") || '';
            var middlename = this.field_manager.get_field_value("middlename") || '';
            var lastname = this.field_manager.get_field_value("lastname") || '';

            var remove_empty_strings = function(array) {
                for (var index = 0; index < array.length; index++) {
                    if (array[index] == '')
                        array.splice(index, 1);
                }
            };

            var names_parts = [ firstname, middlename, lastname ];
            remove_empty_strings(names_parts);
            var fullname = names_parts.join(' ');
            this.field_manager.set_values({'name' : fullname});
        },
    });
    openerp.web.form.custom_widgets.add('concat_name_parts', 'openerp.hr_extra.WidgetConCatCompleteName');
}

I think I have not misused the client side API but I might be wrong, I use the 'field_manager' attribute to listen name-part changes, read/concatenate their values and set the 'name' field.

Please provide some advice to get rid of this weird side effects and point any misusage of the client side API in my code.

Thanks in advance for looking at this.

0
Avatar
Cancelar
yom

you fix the fault thank 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
Another TypeError: ClientWidget is null
web example clientwidget
Avatar
Avatar
1
mar. 15
9066
How to hide the default buttons in a popup window(defined by "ir.actions.client")
new target ir.actions popupwindow clientwidget
Avatar
1
out. 24
1727
Is there any companent which can display the seats of a place like a stadium or a theator?
web chart webkit reactivate clientwidget
Avatar
0
out. 24
1610
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