cundi / blog

push issues as a blog
2 stars 0 forks source link

在Odoo8中设置Many2one的默认值[翻译] #40

Open cundi opened 8 years ago

cundi commented 8 years ago

原文链接:http://www.odoo.yenthevg.com/default-value-many2one-in-odoo-8/

Set default value Many2one in Odoo 8

APRIL 10, 2015YENTHE666

Hi guys,

In this tutorial I will explain you how to set a default value in a Many2one relation. I will add a new field to the quotations view which is a Many2one to all the currencies to demonstrate this. Tip: You can view my sample module here.

1. Creating the field

The first step is to create a new Many2one field that is linked to another model. Simply add a field to your .py file that creates the model. For example:

currency_id_invoices': fields.many2one('res.currency', string="Currency", required=True),

2. Adding the field to view

Then add the field to your view (.xml file):

<field name="currency_id_invoices"/>

If you now go to the view where you’ve added this field you will see a dropdown (Many2one) but there is no default value set.

4s4djio

3. Set default value on Many2one

The next step is to go back to your .py file and add default values. Do this by adding your field between defaults {}.

    #Default values that need to be set
    defaults = {
    'currency_id_invoices': _get_default_currency,
    }

As you can see this links to _get_default_currency which is another function in the same .py file. Create a function above this code which sets the value.

#This function automatically sets the currency to EUR.
    def _get_default_currency(self, cr, uid, context=None):
        res = self.pool.get('res.company').search(cr, uid, [('currency_id','=','EUR')], context=context)
        return res and res[0] or False

So what does this do? When the user wants to create a new quotation and the record opens the defaults {} will be called. This links to the field currency_id_invoices which links to the function that sets the currency in the Many2one. In this function we will go to the res.company table and search for the record where the currency_id is equal to EUR, the currency I want to set by default. When it is found it will be set in the Many2one, otherwise nothing will be set.

The result:

eaakfr9

As you can see the currency is now filled in when you create a new record and the user can still change it whenever he wants to. Want to see this module in action? You can download / view it on my Github. You can find more information about Many2one relations here.