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

Equivalent javascript onLoad() - it is possible when form is loaded?

Inscrever

Seja notificado quando houver atividade nesta publicação

Esta pergunta foi sinalizada
domaindynamiconload
6 Respostas
17099 Visualizações
Avatar
Zbik

This question is related to my previous question: conditional, dynamic field domain.

Example:

<field name="xxx"/>
<field name="yyy_ids" widget="many2many" domain="....DOMAIN......">

I know how to change the domain for yyy_ids when signal change is generated 

@api.onchange('xxx')
def do_xxx(self):

.... here code to change DOMAIN...

return {'domain': {'yyy_ids': ....DOMAIN_VALUE....}}

but how generate onchange signal, at the start, when form will be loaded?

0
Avatar
Cancelar
Zbik
Autor

Thanks, I will check soon.

Avatar
Zbik
Autor Melhor resposta

@Mariusz, PARTLY SOLVED :(. Yes, we now have a new system behavior. Method onchage is fired when a record is created, but if record already exist onchange is not fired, regardless of the default and the new contents of the field xxx.

1
Avatar
Cancelar
Mathieu Laflamme

Any workaround on that? I have the same challenge and I don't know what to do yet :(

Zbik
Autor

I have no new messages. See: https://github.com/odoo/odoo/issues/5199

Avatar
Royal Administrator
Melhor resposta

Here is a way to cause the As Of date to immediately be modified when edit mode is entered:

  - a new FieldAutoJS widget that runs javascript from the xml when it becomes editable
  - declare a new writable field with create and write hooks that clear any attempted writes
  - include the field invisibly on the form and use the autojs widget to set any value
  - in onchange for the new field, if the field is not set, do whatever actions desired to initialize the form, e.g. set date

Javascript:

// 13.0.6.13.2-t8 jimays
// code--1299-edc6-4d86f0db-acb0-f9ee6cefae13--13.0.6.13.2-t8--7.55.20--5.22--XYqqm7*iTnaBOodPqhvqh1
//---------------------------------------------------------------------------------------------

odoo.define('carlisleofficesuites.thermostats', function (require){
'use strict';
var form_widget = require('web.form_widgets');
var core = require('web.core');

// gratitude https://www.odoo.com/forum/help-1/question/equivalent-javascript-onload-it-is-possible-when-form-is-loaded-75863
// gratitude https://www.odoo.com/forum/aide-1/question/how-to-customize-the-onclick-javascript-action-of-an-edit-button-odoo-10-125253
// gratitude https://www.odoo.com/fr_FR/forum/aide-1/question/onchange-method-works-before-something-change-on-field-odoo11-133024
// gratitude https://stackoverflow.com/questions/7650071/is-there-a-way-to-create-a-function-from-a-string-with-javascript
// gratitude https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
// which precisely asks the question, and also
// gratitude https://stackoverflow.com/questions/31187456/which-method-is-called-when-user-click-on-edit-button
// gratitude https://stackoverflow.com/questions/11970035/change-field-value-and-trigger-onchange-event-on-button-press
// gratitude https://www.odoo.com/forum/aide-1/question/how-to-trigger-an-action-onload-of-a-form-view-23593
// gratitude https://www.odoo.com/forum/help-1/question/override-a-field-s-value-on-form-load-108986
// gratitude https://www.odoo.com/forum/aide-1/question/default-method-trigger-my-api-onchange-method-why-151042
// "Since a default value is being loaded..., there is a change in value which will trigger the onchange method.
// So whenever the value in that field changes, even when the default value is loaded, it will trigger the onchange method."
// "Try creating a new invisible field without any value. In your onchange check whether this field is empty or not.
// If it is empty, write some value to this field and exit. If it is not empty continue with your onchange.
// I mentioned this because this is easy to understand. There may be better ways to accomplish the same thing."
// gratitude https://www.odoo.com/forum/aide-1/question/onchange-method-works-before-something-change-on-field-odoo11-133024
// "... when form is load, onchange method is automatically called."
// gratitude http://elico-corp.com.sg/2015/10/01/how-to-tech-dynamically-modify-your-view/
// gratitude https://stackoverflow.com/questions/39424027/adding-a-button-in-tree-view-odoo-8
// gratitude addons/web/static/src/js/views/form_view.js
// gratitude addons/web/static/src/js/views/form_widgets.js
// gratitude FieldsBoolean and FieldsPriority and FieldBinaryFile
//
// Pair with:
//
// <field name="auto" widget="autojs" autojs="your_function();"/?
//
// To force an onchange when Edit is clicked, field can add invisible="1" to the xml
// Couple this code with create and write hooks that always clear the field from the write vals.
//
// <field name="auto" widget="autojs" autojs="return 'auto';" invisible="1"/>
//
// as_of = fields.Datetime('As Of', required=True)
// auto = fields.Char('Auto')
//
// @api.onchange('auto')
// def onchange_auto(self):
// if not self.auto:
// # the as_of is visibly adjusted when Edit is clicked
// self.as_of = fields.datetime.now()
//
// @api.model
// def update_write_vals(self, vals):
// vals['as_of'] = fields.Datetime.now()
// if 'auto' in vals:
// del vals['auto']
//
// @api.model
// @api.returns('self', lambda value: value.id)
// def create(self, vals):
// self.update_write_vals(vals)
// return super(ThisModel, self).create(vals)
//
// @api.multi
// def write(self, vals):
// self.update_write_vals(vals)
// super(ThisModel, self).write(vals)

var FieldAutoJS = form_widget.FieldChar.extend({
start: function(){
true && console.log('FieldAuto.start: this.field: ' + JSON.stringify(this.field));
true && console.log('FieldAuto.start: this.options.model_field: ' + JSON.stringify(this.options.model_field));
var self = this;
var change_effective_readonly = function(){
if(!self.get("effective_readonly")){
true && console.log('FieldAuto: Auto field has become editable.');
if('autojs' in self.node.attrs){
true && console.log('FieldAuto: Setting value with javascript: ' + self.node.attrs.autojs);
var autojs_function = new Function(self.node.attrs.autojs);
var newValue = autojs_function(self);
var oldValue = self.get_value();
true && console.log('FieldAuto: Triggering change:value, oldValue: ' + oldValue + ', newValue: ' + newValue);
self.trigger("change:value", self, { oldValue: oldValue, newValue: newValue });
self.render_value();
}
}
};
this.on("change:effective_readonly", this, change_effective_readonly);
change_effective_readonly.call(this);
this._super.apply(this, arguments);
},
});

core.form_widget_registry.add('autojs', FieldAutoJS);
});

Python

class CarlisleOfficeSuites_Thermostat(models.Model):
_name = 'carlisleofficesuites.thermostat'
_rec_name = 'zone'

zone = fields.Char('Zone', required=True)

# 13.0.6.13.2-t8 The auto field is always blank in the database and always auto-set by the javascript upon entering form view edit mode.
# This trick makes the form have a changed value as soon as it opens for edit, which visibly pre-adjusts the As Of, which is cute,
# and more importantly marks the form as changed so a save actually calls the write hook, and the latest draft settings become active.

as_of = fields.Datetime('As Of', required=True)
auto = fields.Char('Auto')

@api.onchange('auto')
def onchange_auto(self):
_logger.debug('onchange_auto, self.auto: ' + unicode(self.auto))
if not self.auto:
​ # the as_of is visibly adjusted when Edit is clicked
            self.as_of = fields.datetime.now()
    @api.model
def update_write_vals(self, vals):
vals['as_of'] = fields.Datetime.now()
if 'auto' in vals:
del vals['auto']
    @api.model
@api.returns('self', lambda value: value.id)
def create(self, vals):
self.update_write_vals(vals)
return super(CarlisleOfficeSuites_Thermostat, self).create(vals)

@api.multi
def write(self, vals):
self.update_write_vals(vals)
super(CarlisleOfficeSuites_Thermostat, self).write(vals)
return True
0
Avatar
Cancelar
Avatar
Mariusz Mizgier
Melhor resposta

Did you try: 1. apply this patch - https://github.com/odoo/odoo/commit/2067a206ecba9a8dbf7f76a55926be964e580e7e 2. move your xxx before yyy_ids in form view 3. set _defaults for xxx to False Didn't check that, but that should work - if not, maybe change in logic (defaults = True) so that this field does change it's value.

0
Avatar
Cancelar
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
use dynamic value in domain
domain dynamic
Avatar
Avatar
Avatar
2
mai. 24
8614
dynamic domain in one2many Resolvido
domain one2many dynamic
Avatar
Avatar
Avatar
2
mai. 24
10090
How to set many2one domain based on many2many field in odoo
domain many2one dynamic
Avatar
Avatar
1
jan. 22
12857
Dynamic Domain in Windows Action Resolvido
domain purchase_order dynamic
Avatar
Avatar
1
jul. 20
16850
Dynamically Restrict Choices in One2Many Relation Based on Already Selected Values
domain domain_filter dynamic attributes
Avatar
0
mar. 24
1872
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