Skip to Content
Odoo Menu
  • Sign in
  • Teste-o gratuitamente
  • Aplicações
    Finanças
    • Contabilidade
    • Faturação
    • Despesas
    • Folha de cálculo (BI)
    • Documentos
    • Assinatura eletrónica
    Vendas
    • CRM
    • Vendas
    • POS para lojas
    • POS para restaurantes
    • Subscrições
    • Aluguer
    Sites
    • Criador de Sites
    • Comércio eletrónico
    • Blogue
    • Fórum
    • Chat em direto
    • e-Learning
    Cadeia de abastecimento
    • Inventário
    • Produção
    • PLM
    • Compras
    • Manutenção
    • Qualidade
    Recursos Humanos
    • Colaboradores
    • Recrutamento
    • Ausências
    • Avaliações
    • Indicações
    • Frota
    Marketing
    • Marketing social
    • Marketing por e-mail
    • Marketing através de SMS
    • Eventos
    • Automação de Marketing
    • Inquéritos
    Serviços
    • Projeto
    • Registos de Horas
    • Assistência no local
    • Assistência
    • Planeamento
    • Agendamentos
    Produtividade
    • Conversas
    • Inteligência artificial
    • IoT
    • VoIP
    • Informação
    • WhatsApp
    Aplicações de terceiros Odoo Studio Plataforma Odoo Cloud
  • Setores
    Retalho
    • Livraria
    • Loja de roupa
    • Loja de móveis
    • Mercearia
    • Loja de ferragens
    • Loja de brinquedos
    Alimentação e hotelaria
    • Bar e pub
    • Restaurante
    • Comida rápida
    • Casa de hóspedes
    • Distribuidor de bebidas
    • Hotel
    Imobiliário
    • Agência imobiliária
    • Gabinete de arquitectura
    • Construção
    • Gestão imobiliária
    • Jardinagem
    • Associação de proprietários
    Consultoria
    • Gabinete de contabilidade
    • Parceiro da Odoo
    • Agência de marketing
    • Sociedade de advogados
    • Aquisição de talentos
    • Auditoria e certificação
    Produção
    • Têxtil
    • Metal
    • Móveis
    • Alimentação
    • Cervejaria
    • Brindes promocionais
    Saúde e bem-estar
    • Clube desportivo
    • Ótica
    • Ginásio
    • Profissionais de bem-estar
    • Farmácia
    • Cabeleireiro
    Ofícios
    • Handyman
    • Hardware e suporte técnico
    • Sistemas de energia solar
    • Sapataria
    • Serviços de limpeza
    • Serviços de climatização
    Outros
    • Organização sem fins lucrativos
    • Agência do ambiente
    • Aluguer de painéis publicitários
    • Estúdio de fotografia
    • Aluguer de bicicletas
    • Revendedor de software
    Explorar todos os setores
  • Comunidade
    Aprender
    • Tutoriais
    • Documentação
    • Certificações
    • Treino
    • Blogue
    • Podcast
    Capacitar a educação
    • Programa de formação
    • Scale Up! O jogo de negócios
    • Visite a Odoo
    Obter o software
    • Transferir
    • Comparar Edições
    • Versões
    Colaborar
    • Github
    • Fórum
    • Eventos
    • Traduções
    • Torne-se um parceiro
    • Serviços para parceiros
    • Registe a sua empresa contabilística
    • Programa de afiliados
    Obter serviços
    • Encontre um parceiro
    • Encontre um contabilista
    • Contacte um consultor
    • Serviços de implementação
    • Referências de clientes
    • Apoio
    • Atualizações
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar uma demonstração
  • Preços
  • Ajuda
You need to be registered to interact with the community.
All Posts People Badges
Tags (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Tags (View all)
odoo accounting v14 pos v15
About this forum
Help

RPC with new v8 API (Call Python function from JavaScript examples) Odoo 8

Subscribe

Get notified when there's activity on this post

This question has been flagged
javascriptv8rpcexamplesv8.0
1 Reply
17025 Views
Avatar
Temur


in the new API, if you've to deal with ids/recordsets then for python function definition choose decorator:

  • @api.multi -to get recordset in your function

  • @api.one -to get browse_records one by one in your function

in examples I'll use @api.multi but @api.one also may be used to deal with ids, depending on requirements.

if it's simple function that does not have to deal with records/ids then for python function choose decorator:

  • @api.model -Allows to be polite with old style api

  • @api.multi -you can use it as well, just pass [ ] (empty array) as first argument in javascript...


an example model:

class my_model(models.Model):
_name = "my.model"

name = fields.Char('Name')

@api.multi
def foo_manipulate_records_1(self):
""" function returns list of tuples (id,name) """
return [(i.id,i.name) for i in self]

@api.multi
def foo_manipulate_records_2(self, arg1, arg2)
#here you can take advantage of "self" recordset and same tie use aditional arguments "arg1", "arg2"
pass

@api.model
def bar_no_deal_with_ids(self, arg1, arg2):
""" concatenate arg1 and arg2 """
return unicode(arg1) + unicode(arg2)


Odoo RPC examples:

assume that "list_of_ids" variable contains list(array) of ids of existing records of my.model model.

- call of function foo_manipulate_records_1 decorated with @api.multi:

new instance.web.Model("my.model")
.call( "foo_manipulate_records_1", [list_of_ids])
.then(function (result) {
// do something with result
});

-call of function foo_manipulate_records_2 decorated with @api.multi:

new instance.web.Model("my.model")
.call( "foo_manipulate_records_2", [list_of_ids, arg1, arg2])
.then(function (result) {
// do something with result
});

-call of function bar_no_deal_with_ids decorated with @api.model:

new instance.web.Model("my.model")
.call( "bar_no_deal_with_ids", [arg1, arg2])
.then(function (result) {
// do something with result
});


also if it has some sense depending on implementation, then you can call function decorated with @api.multi even if you have not to deal with ids (just pass empty array in place of ids, as firs element of argument list):

new instance.web.Model("my.model")
.call( "foo_manipulate_records_2", [[], arg1, arg2])
.then(function (result) {
// do something with result
});

this way may be useful in some cases, as undecorated function in v8.0 api is considered as @api.multi (as @api.multi is a default decorator)


except of two parameters to RPC call that I've used in examples (the function name and argument list), you can use third parameter -a dictionary of keyword arguments. it's highly recommended to turn around the context, as it may change behavior of remote procedure (localization, etc.). below I'll rewrite the last example with context argument in rpc call (same may be applied to all examples)

var self = this;
new instance.web.Model("my.model")
.call("foo_manipulate_records_2", [[], arg1, arg2], {'context':self.session.user_context})
.then(function (result) {
// do something with result
});

(of course you can use custom context as well instead of turning around the existing one, if that's a requirement.)


references: Odoo RPC documentation, Odoo new API method decorators

1
Avatar
Discard
Avatar
Temur
Author Best Answer

Originally were posted here as answer.

1
Avatar
Discard
Osval Reyes

@Temur the url is broken, do you still have the solution for this?

Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Sign up
Related Posts Replies Views Activity
How to find the view_id using rpc call from JavaScript
javascript rpc
Avatar
Avatar
2
jan. 23
8303
Catch is not a function
javascript rpc
Avatar
0
fev. 21
5847
rpc.query doesn't work
javascript rpc odoo
Avatar
1
jul. 26
411
How to use RPC query in JavaScript with search method in Odoo 11 / 12?
javascript rpc odoov11
Avatar
Avatar
1
set. 21
23037
rpc.query function in js not working when I am not logged in Solved
javascript rpc v14
Avatar
Avatar
2
abr. 21
7190
Comunidade
  • Tutoriais
  • Documentação
  • Fórum
Código aberto
  • Transferir
  • Github
  • Runbot
  • Traduções
Serviços
  • Alojamento Odoo.sh
  • Apoio
  • Atualizar Versão
  • Desenvolvimentos personalizados
  • Educação
  • Encontre um contabilista
  • Encontre um parceiro
  • Torne-se um parceiro
Sobre nós
  • A Nossa Empresa
  • Ativos da marca
  • Contacte-nos
  • Trabalhos
  • Eventos
  • Podcast
  • Blogue
  • 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) Português română русский язык Slovenský jazyk Slovenščina Español (América Latina) Español Svenska ภาษาไทย Türkçe українська Tiếng Việt

O Odoo é um conjunto de aplicações empresariais de código aberto que abrange todas as necessidades da sua empresa: CRM, comércio eletrónico, contabilidade, gestão de inventário, ponto de venda, gestão de projetos, etc.

A proposta de valor única do Odoo é ser, ao mesmo tempo, muito fácil de utilizar e totalmente integrado.

Website made with

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