Odoo Help

Welcome!

This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.

1

How to save and update custom settings in Odoo? (TransientModel)

By
Yenthe
on 11/26/15, 8:22 AM 1,765 views

Hi guys,

I've just created a new custom settings menuitem under Settings (just like other ones exist for Sales, Financial, ..) I create a new TransientModel which holds the temp data like this:

class ResConfigOutlook(models.TransientModel):
    _name = 'outlook.sync.settings'
    _inherit = 'res.config.settings'

outlook_id = fields.Many2one('outlook.sync', string='Outlook', required=True, defaults=lambda self,cr,uid,c: self.pool.get('outlook.sync').search(cr, uid, [], context=c)[0]) sync_calendars = fields.Boolean(related='outlook_id.sync_calendars', default=False) sync_contacts = fields.Boolean(related='outlook_id.sync_contacts', default=False) default_backwards_sync = fields.Integer(related='outlook_id.default_backwards_sync', default='1') default_forward_sync = fields.Integer(related='outlook_id.default_forward_sync', default='3') def on_change_outlook_id(self, cr, uid, ids, outlook_id, context=None): if not outlook_id: #This means it was never configged - default values here! return {'value': {'sync_calendars': False, 'sync_contacts': False, 'default_backwards_sync': 1, 'default_forward_sync': 3}} outlook_data = self.pool.get('outlook.sync').read(cr, uid, [outlook_id], [], context=context)[0] values = { 'sync_calendars': outlook_data['sync_calendars'], 'sync_contacts': outlook_data['sync_contacts'], 'default_backwards_sync': outlook_data['default_backwards_sync'], 'default_forward_sync': outlook_data['default_forward_sync']} for fname, v in outlook_data.items(): if fname in self._columns: values[fname] = v[0] if v and self._columns[fname]._type == 'many2one' else v return {'value': values}

def create(self, cr, uid, vals, context=None): config_id = super(ResConfigOutlook, self).create(cr, uid, vals, context=context) self.write(cr, uid, config_id, vals, context=context) return config_id

The outlook_id (many2one) links to the model that will actually hold the data, outlook.sync which contains the following fields:

class Settings_holder(models.Model):
    _name = 'outlook.sync'
    sync_calendars = fields.Boolean('Info')
    sync_contacts = fields.Boolean('Info')
    default_backwards_sync = fields.Integer('Info')
    default_forward_sync = fields.Integer('Info')

I then created a new view to show all these values:

<record id="outlook_sync_config" model="ir.ui.view">
<field name="name">Your configuration</field>
<field name="model">outlook.sync.settings</field>
<field name="arch" type="xml">
    <form string="Outlook configuration" class="oe_form_configuration">
         <header>
             <button string="Save" type="object"name="execute" class="oe_highlight"/>
             or 
             <button string="Cancel" type="object" name="cancel" class="oe_link"/>
      </header>
<field name="outlook_id" invisible="True" on_change="on_change_outlook_id(outlook_id)"/>; <group string="Synchronise"> <field name="sync_calendars" string="Synchronise calendars"/> <field name="sync_contacts" string="Synchronise contacts"/> </group> <group string="Outlook settings"> <field name="default_backwards_sync" string="Backwards sync"/> <field name="default_forward_sync" string="Forward sync"/>
</group> </form> </field> </record>

Now this all looks good, until I hit the 'Save' button. I will then get the following error:

Integrity Error

The operation cannot be completed, probably due to the following: - deletion: you may be trying to delete a record while other records still reference it - creation/update: a mandatory field is not correctly set
[object with reference: outlook_id - outlook.id]

But now I'm wondering.. how do I transfer the data from the TransientModel to the normal model and the other way around? I seem to be doing something wrong.

Yenthe

4

Axel Mendoza

--Axel Mendoza--
10205
| 7 7 8
Camaguey, Cuba
--Axel Mendoza--

DevOps - Full stack - Software Architect - Developer - Technology Integrator

I could help you to develop anything and solve complex problems based on technologies, integrations and tricky stuffs mostly in Python with OpenERP/Odoo, Zato, Django and many others frameworks programming languages and technologies.

I offers consulting services to anyone with an unanswered questions or needs for customizations. Think about it, maybe it's better to have an expert to solve your issues and projects than having a full time employee trying to understand what to do an how

Reach me at aekroft@gmail.com

Axel Mendoza
On 11/26/15, 12:48 PM

Hi @Yenthe

Take as example website settings and their use of related on settings fields

------------------------------------------------------------------------------- Changes---------------------------------------------------------------------------------

# -*- coding: utf-8 -*-
from openerp import models, fields, api
from openerp.osv import osv

#Import logger
import logging
#Get the logger
_logger = logging.getLogger(__name__)

class Settings_holder(models.Model):
_name = 'outlook.sync'
sync_calendars = fields.Boolean('Sync Odoo and Outlook calendars', default=False)
sync_contacts = fields.Boolean('Sync Odoo and outlook contacts')
default_backwards_sync = fields.Integer('Months of backwards syncing')
default_forward_sync = fields.Integer('Months of forward syncing')


class ResConfigOutlook(models.TransientModel):
_name = 'outlook.sync.settings'
_inherit = 'res.config.settings'

outlook_id = fields.Many2one('outlook.sync', string='Outlook')
sync_calendars = fields.Boolean(related='outlook_id.sync_calendars')
sync_contacts = fields.Boolean(related='outlook_id.sync_contacts')
default_backwards_sync = fields.Integer(related='outlook_id.default_backwards_sync')
default_forward_sync = fields.Integer(related='outlook_id.default_forward_sync')

def on_change_outlook_id(self, cr, uid, ids, outlook_id, context=None):
_logger.critical('ON_CHANGE_OUTLOOK_ID')
if not outlook_id:
#This means it was never configged - default values here!
return {'value': {'sync_calendars': False, 'sync_contacts': False, 'default_backwards_sync': 1, 'default_forward_sync': 3}}
outlook_data = self.pool.get('outlook.sync').read(cr, uid, [outlook_id], [], context=context)[0]
values = {
'sync_calendars': outlook_data['sync_calendars'],
'sync_contacts': outlook_data['sync_contacts'],
'default_backwards_sync': outlook_data['default_backwards_sync'],
'default_forward_sync': outlook_data['default_forward_sync']
}
for fname, v in outlook_data.items():
if fname in self._columns:
values[fname] = v[0] if v and self._columns[fname]._type == 'many2one' else v
return {'value': values}

def create(self, cr, uid, vals, context=None):
_logger.critical('CREATE' + str (vals))
config_id = super(ResConfigOutlook, self).create(cr, uid, vals, context=context)
self.write(cr, uid, config_id, vals, context=context)
return config_id

_defaults = {
'outlook_id': lambda self,cr,uid,c: self.pool.get('outlook.sync').search(cr, uid, [], context=c)[0]
}

I create a view, action and menu for test it

<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>

<record id="view_website_config_settings" model="ir.ui.view">
<field name="name">Website settings</field>
<field name="model">outlook.sync.settings</field>
<field name="arch" type="xml">
<form string="Configure Outlook" class="oe_form_configuration">
<header>
<button string="Apply" type="object" name="execute" class="oe_highlight"/>
or
<button string="Cancel" type="object" name="cancel" class="oe_link"/>
</header>
<div>
<field name="outlook_id" invisible="True" on_change="on_change_outlook_id(outlook_id)"/>
<group string="Synchronise">
<field name="sync_calendars" />
<field name="sync_contacts"/>
</group>
<group string="Outlook settings">
<field name="default_backwards_sync"/>
<field name="default_forward_sync"/>
</group>
</div>
</form>
</field>
</record>

<record id="action_outlook_configuration" model="ir.actions.act_window">
<field name="name">Outlook Settings</field>
<field name="res_model">outlook.sync.settings</field>
<field name="view_mode">form</field>
<field name="target">inline</field>
</record>

<menuitem id="menu_outlook_configuration" parent="base.menu_config"
sequence="90" action="action_outlook_configuration"/>

</data>
<data noupdate="1">
<record id="default_outlook" model="outlook.sync">
<field name="sync_calendars" eval="True"/>
<field name="sync_contacts" eval="True"/>
<field name="default_backwards_sync" type="int">1</field>
<field name="default_forward_sync" type="int">1</field>
</record>
</data>

</openerp>

As you see on the end of the xml there is the definition/creation of the record to be updated in the settings view, the one obtained from the _defaults for outlook_id and passed to the onchange. I test it and it's working


@Axel I've updated my question with the newest code - I'm almost there I think. Now I get an integrity Error.. Any idea?

Yenthe
on 11/27/15, 5:54 AM

@Axel update #2: no more errors but the values do not seem to be saved / migrated from one table to another and are not shown to the user.

Yenthe
on 11/27/15, 7:39 AM

Hey.. i don't see any relation to user from outlook.setting model... Maybe if that is supposed to be for users, you would like to make class outlook_settings(models.Model): _inherit = 'res.users' ??? that way it will extend user class and should be easily wievable to users...

Bole
on 11/27/15, 12:23 PM

@Yenthe I test it your code and I will update my answer with the changes that works

Axel Mendoza
on 11/27/15, 1:26 PM

@Bole: there is no relation to an user, these are system wide settings. So this only has to be done once for the whole company! :) @Axel: thanks a lot for the great answer! This is a nice approach to get things working and I really like it. +1 and accepted. Thanks a lot for your time :)

Yenthe
on 11/28/15, 5:28 AM

Thanks a lot for you guys, all of this problems and solutions will help for those who will look for similar problems in the future

Axel Mendoza
on 11/29/15, 2:44 AM

Exactly! One thing I'm wondering: couldn't we rewrite the defaults to V8/V9 API style?

Yenthe
on 11/29/15, 7:26 AM

In the new api it need to be like this:
outlook_id = fields.Many2one('outlook.sync', string='Outlook', required=True, default=lambda self: self.env['outlook.sync'].search([])[0])

Axel Mendoza
on 11/29/15, 3:20 PM

Hi @Yenthe, thanks for your solution, I almost done with my custom setting function.But I have got one problem -- the cancel button also save the settings, seems that the TransientModel auto save data when any button clicked. One more question, for your code above, since there is a default function for outlook_id, what's the purpose of the on_change function.

jianxin
on 1/6/16, 9:48 AM
1

Emipro Technologies Pvt. Ltd.

--Emipro Technologies Pvt. Ltd.--
Tiny ERP Pvt Ltd
http://www.odoo.com
5975
| 6 7 8
Rajkot, India
--Emipro Technologies Pvt. Ltd.--

Being an emerging leader in IT market since 2011, Emipro Technologies Pvt. Ltd. has been providing a wide range of business solutions in Odoo & Magento. We are pleased to have a large pool of contented customers with our meticulous work in the domain of ERP & e-Commerce. A ray of relief & satisfaction to  our customers heart by our successful deployment in their organization, purely represents our success in Odoo platform. Hence, we take pride for being an Odoo partner with a vision of expanding our strategic alliances with our customers to offer them high value-added, trustworthy & cost effective solutions.

 

Since establishment, our business has span across 11 countries of the world. Our customers are companies of all sizes ranging from start-ups to large enterprises, who realize that they need a professional business solutions to generate revenue streams, establish proper communication channels or streamline business operations. Standing with strong determination of customer satisfaction, observing each minute detail of their business processes, providing proper guidance and moving forth to develop product accordingly adds our value and reliability among our customers. 

 

We are blessed with efficient, passionate & eclectic young developers who have come across almost all kinds of business profiles, working with full dedication, applying creativity & new features in existing modules and completing customer's projects successfully on predefined target. Our in-depth knowledge while giving business solutions in Odoo allows us to offer following services to our customers :

 

  • Consulting
  • Installation, Configuration & Customization
  • Training & Support
  • Maintenance
  • Upgradation
  • Documentation
  • Crafting community modules
  • Drafting videos on demand
  • Smart Apps development

We will be :) to welcome you @ www.emiprotechnologies.com to solve any kind of your business needs around Odoo. However we are just an inch away from you by email info@emiprotechnologies.com or a tweet to @EmiproTech

Emipro Technologies Pvt. Ltd.
On 11/28/15, 12:10 AM

Hello Yenthe,

You have done correct implementation. But you just missed on method which is very important and define inside "res.config.setting" model and called when user click on "Apply" button. That is looks like below.

 @api.multi
def execute(self):
res = super(ResConfigOutlook,self).execute()
...... #Your code
return res

As your code you have to just write down one method as like below and your task is over. 

 @api.multi
def execute(self):
outlook_object = self.outlook_id
values = {}
res = super(ResConfigOutlook,self).execute()
if outlook_object:
values['sync_calendars'] = self.sync_calendars or False
values['sync_contacts'] = self.sync_contacts or False
values['default_backwards_sync'] = self.default_backwards_sync or False
values['default_forward_sync'] = self.default_forward_sync or False
outlook_object.write(values)

return res

"""how do I transfer the data from the TransientModel to the normal model ? """. There is one method named "execute" is responsible for transfer the data which is define inside res.config.settings model. I am sure that you get your answer and fix your issue.

Thanks.


Thanks a lot for your answer and time Emipro! Your solution works with some minor changes but I do like the method from Axel a bit more. I've upvoted your answer too though. Sorry that I can't accept both!

Yenthe
on 11/28/15, 5:29 AM

It's fine. As Axel's answer is better then me. I will upvote his answer too.

Emipro Technologies Pvt. Ltd.
on 11/28/15, 11:28 PM

Your Answer

Please try to give a substantial answer. If you wanted to comment on the question or answer, just use the commenting tool. Please remember that you can always revise your answers - no need to answer the same question twice. Also, please don't forget to vote - it really helps to select the best questions and answers!

About This Community

This community is for professionals and enthusiasts of our products and services. Read Guidelines

Question tools

2 follower(s)

Stats

Asked: 11/26/15, 8:22 AM
Seen: 1765 times
Last updated: 11/28/15, 11:28 PM