Overslaan naar inhoud
Odoo Menu
  • Aanmelden
  • Probeer het gratis
  • Apps
    Financiën
    • Boekhouding
    • Facturatie
    • Onkosten
    • Spreadsheet (BI)
    • Documenten
    • Ondertekenen
    Verkoop
    • CRM
    • Verkoop
    • Kassasysteem winkel
    • Kassasysteem Restaurant
    • Abonnementen
    • Verhuur
    Websites
    • Websitebouwer
    • E-commerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Bevoorradingsketen
    • Voorraad
    • Productie
    • PLM
    • Inkoop
    • Onderhoud
    • Kwaliteit
    Personeelsbeheer
    • Werknemers
    • Werving & Selectie
    • Verlof
    • Evaluaties
    • Aanbevelingen
    • Wagenpark
    Marketing
    • Social media Marketing
    • E-mailmarketing
    • SMS Marketing
    • Evenementen
    • Marketingautomatisering
    • Enquêtes
    Diensten
    • Project
    • Urenstaten
    • Buitendienst
    • Helpdesk
    • Planning
    • Afspraken
    Productiviteit
    • Chat
    • Goedkeuringen
    • IoT
    • VoIP
    • Kennis
    • WhatsApp
    Apps van derden Odoo Studio Odoo Cloud Platform
  • Bedrijfstakken
    Detailhandel
    • Boekhandel
    • kledingwinkel
    • Meubelzaak
    • Supermarkt
    • Bouwmarkt
    • Speelgoedwinkel
    Food & Hospitality
    • Bar en Pub
    • Restaurant
    • Fastfood
    • Gastenverblijf
    • Drankenhandelaar
    • Hotel
    Vastgoed
    • Makelaarskantoor
    • Architectenbureau
    • Bouw
    • Vastgoedbeheer
    • Tuinieren
    • Vereniging van eigenaren
    Consulting
    • Accountantskantoor
    • Odoo Partner
    • Marketingbureau
    • Advocatenkantoor
    • Talentenwerving
    • Audit & Certificering
    Productie
    • Textiel
    • Metaal
    • Meubels
    • Eten
    • Brewery
    • Relatiegeschenken
    Gezondheid & Fitness
    • Sportclub
    • Opticien
    • Fitnesscentrum
    • Wellness-medewerkers
    • Apotheek
    • Kapper
    Trades
    • Klusjesman
    • IT-hardware & support
    • Zonne-energiesystemen
    • Schoenmaker
    • Schoonmaakdiensten
    • HVAC-diensten
    Andere
    • Non-profit organisatie
    • Milieuagentschap
    • Verhuur van Billboards
    • Fotograaf
    • Fietsleasing
    • Softwareverkoper
    Browse all Industries
  • Community
    Leren
    • Tutorials
    • Documentatie
    • Certificeringen
    • Training
    • Blog
    • Podcast
    Versterk het onderwijs
    • Onderwijs- programma
    • Scale Up! Business Game
    • Bezoek Odoo
    Download de Software
    • Downloaden
    • Vergelijk edities
    • Releases
    Werk samen
    • Github
    • Forum
    • Evenementen
    • Vertalingen
    • Word een Partner
    • Services for Partners
    • Registreer je accountantskantoor
    Diensten
    • Vind een partner
    • Vind een boekhouder
    • Een adviseur ontmoeten
    • Implementatiediensten
    • Klantreferenties
    • Ondersteuning
    • Upgrades
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Vraag een demo aan
  • Prijzen
  • Help

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

  • CRM
  • e-Commerce
  • Boekhouding
  • Voorraad
  • PoS
  • Project
  • MRP
All apps
Je moet geregistreerd zijn om te kunnen communiceren met de community.
Alle posts Personen Badges
Labels (Bekijk alle)
odoo accounting v14 pos v15
Over dit forum
Je moet geregistreerd zijn om te kunnen communiceren met de community.
Alle posts Personen Badges
Labels (Bekijk alle)
odoo accounting v14 pos v15
Over dit forum
Help

Create new Many2One records in @api.onchange method (2nd try)

Inschrijven

Ontvang een bericht wanneer er activiteit is op deze post

Deze vraag is gerapporteerd
many2oneonchangenewapi
5 Antwoorden
20336 Weergaven
Avatar
Tzin

Hello,

I am new to Odoo and I struggle with the new Odoo API. I am trying to create new records on a Many2One field in an @api.onchange method. It is a custom module so I will simplify by providing a made up example. 

Say that I am building a new Order that has Lines. The lines are defined via a Many2One field called 'line':

class Order(models.Model):

    name="mymodule.order"

    line = fields.One2many('mymodule.line',
                                inverse_name="order_id",         
                                string="Lines")

    partner_id = fields.....

    .....

I want to generate new lines as soon as the user selects or changes the partner_id of the order. To do so, I have implemented an @api.onchance method that looks somewhat like this:

@api.onchange('partner_id')
 def onchange_equipment_type_id(self):
        """ Updates the order lines"""
        if self.line:
            self.line.unlink()
        for val in self.bogus_values: #some bogus list that supposedly tells me how many lines I need to create
            self.line.create({'name':val.name, 'order_id':self.id, ....})

The above approach does not work. First of all, as far as I understand CREATE will actually create records to the DB. I do not want that. I simply want to add some order lines as if I clicked few times on 'Add an item' in a table. The actual creation of the lines shall happen when the user clicks the Save button on the order. So what method shall I use? How can I 'add' records to the line field without writing to the DB at this point? 

The second problem that I face is that self.id is NewId. Now as per my understanding this is normal for New records. But I actually get self.id as NewID even for entries that have been saved and I open them in edit mode. Anyways, for the case when the order has not been saved yet, I still need to add lines. So my major issue is how to add lines to my Many2One field as part of my onchange method without triggering a DB write. 

 

Let me reiterate again - I want to create a Many2One not as part of the 'parent' object create method. I want to do this as an onchange event.  I want to generate the lines as soon as I change the partner. Imagine that for each partner there is a predefined set of lines, for example based on favorite products. So as soon as the one changes the partner id, a new list of favorite products will be retrieved (for the selected partner), the existing order lines must be deleted and new lines (for the new product set) shall be generated. All this shall happen prior to the user hitting the Save button on the order object. Actually the user can change partners several times priori to saving the order. 

I hope that my question makes some sense. 

Thank you in advance for your help.

2
Avatar
Annuleer
Avatar
Tzin
Auteur Beste antwoord

Hi, I solved this problem some time in the following manner:

@api.onchange('partner_id') 
def _onchange_equipment(self):
    lines =[]
     
    for val in self.bogus_values:
        line_item = {
                      'attr1': val.name,
                      'attr2': val.a1,
                      ...                             
                }
        lines += [line_item]
    self.update({'line': lines})

In my very humble oppinion this works better than the proposal of Stefano (at least for my scenario). After all, the user can change the partner many time prior to saving the order. The create will probably insert new records in the DB. We do not want this to happen each time the user changes the partner. Stefano, please correct me if I am wrong and thank you for your response.

1
Avatar
Annuleer
Avatar
Jairo Llopis
Beste antwoord

Do not use create(). Use new() instead. It's also more object-oriented than update().

In your case, replace self.line.create({'name':val.name, 'order_id':self.id, ....}) with self.line |= self.line.new({'name':val.name ....})

5
Avatar
Annuleer
Jairo Llopis

It should be documented IMHO. I opened bug https://github.com/odoo/odoo/issues/5611

Andre

Did it for me! Thanks.

sharon shen

new doesn't work for me, only create works... im on odoo 8

Avatar
Yogesh
Beste antwoord

Try this, it will work

@api.onchange('partner_id')
 def onchange_equipment_type_id(self):
        """ Updates the order lines""
        for val in self.bogus_values: #some bogus list that supposedly tells me how many lines I need to create
            self.line  = [((0, 0, {'name':val.name, 'order_id':self.id, ....}))]

 

2
Avatar
Annuleer
Avatar
Raghupathy.k
Beste antwoord

Hai Tzin

I have solved it by the following code in odoo 15

@api.onchange('customer_id')
def _onchange_customer_id(self):
    lines =[]
    for rec in self.customer_id.site_ids:
        result ={'name':rec.name}
        lines.append((0,0, result))
    self.site_ids = lines

0
Avatar
Annuleer
Avatar
Stefano Del Gobbo
Beste antwoord

I need something similar.

I have to fill BoM list on selecting product.

@api.onchange('product_id')
 def onchange_product_id(self):
        """ Updates the BOM lines"""
        if self.line:
        for val in self.bom_template: #value on a BOM template that cointain products
            self.line.create({'name':val.name, 'order_id':self.id, ....})

 

Any help?

Thanks

0
Avatar
Annuleer
Geniet je van het gesprek? Blijf niet alleen lezen, doe ook mee!

Maak vandaag nog een account aan om te profiteren van exclusieve functies en deel uit te maken van onze geweldige community!

Aanmelden
Gerelateerde posts Antwoorden Weergaven Activiteit
when i select the category in the sale list the regarding product must shown in the product id in the bill list by onchange
many2one onchange
Avatar
0
dec. 18
13
Onchange many2one partner_bank_id Opgelost
many2one onchange
Avatar
Avatar
1
mei 16
5029
Create dynamic selection on many2one fields with onchange
many2one onchange dynamic
Avatar
Avatar
1
sep. 23
7327
Create new Many2One records in @api.onchange method
many2one create onchange
Avatar
Avatar
1
aug. 22
8811
How to Use Many2one Field as selection for details?
many2one selection onchange
Avatar
Avatar
1
jul. 19
7787
Community
  • Tutorials
  • Documentatie
  • Forum
Open Source
  • Downloaden
  • Github
  • Runbot
  • Vertalingen
Diensten
  • Odoo.sh Hosting
  • Ondersteuning
  • Upgrade
  • Gepersonaliseerde ontwikkelingen
  • Onderwijs
  • Vind een boekhouder
  • Vind een partner
  • Word een Partner
Over ons
  • Ons bedrijf
  • Merkelementen
  • Neem contact met ons op
  • Vacatures
  • Evenementen
  • Podcast
  • Blog
  • Klanten
  • Juridisch • Privacy
  • Beveiliging
الْعَرَبيّة 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 is een suite van open source zakelijke apps die aan al je bedrijfsbehoeften voldoet: CRM, E-commerce, boekhouding, inventaris, kassasysteem, projectbeheer, enz.

Odoo's unieke waardepropositie is om tegelijkertijd zeer gebruiksvriendelijk en volledig geïntegreerd te zijn.

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