如何在 Odoo 中将值和翻译从一个字段复制到另一个字段?

How to copy value and translations from one field to another in Odoo?

假设您想用默认值填充 sale.order 表单中的字段,相同的文本将用于 Odoo 中使用的每个公司。有时,通常的处理方式是使用 res.company 模型中的公共字段。其他选项是在选择客户时在 res.partner 表单中添加一个填充其他内容的字段。

但我发现的问题是:如果我想获取该字段的翻译,而这些翻译已经在原始翻译中,我将不得不手动完成,继承ir.translation 的创建方法。当该字段被复制到 sale.order 表单时,会创建当前使用的语言的记录,因此我利用它来创建其余记录。有更好的方法吗?

此外,我想补充一点,保存记录后,我按世界图标再次翻译文本,新的翻译是用当前文本创建的。所以我需要在每条 sale.order 条记录上重新翻译所有内容。

我在 ir.translation 模型中为一个简单的文本字段执行了此操作,以便创建其他语言的翻译。字段 field_to_translate 两边都是可翻译的:

@api.model
def create(self, vals):
    record = super(IrTranslation, self).create(vals)
    name = vals.get('name', False)  # name of the field to translate
    lang = vals.get('lang', False)  # creating record for this language
    if 'context' in dir(self.env):
        cur_lang = self.env.context.get('lang', False)  # current used language
        if name == 'sale.order,field_to_translate' and lang == cur_lang:
            langs = self.env['ir.translation']._get_languages()
            langs = [l[0] for l in langs if l[0] != cur_lang]   # installed languages

            for l in langs:
                if self.env.user.company_id.field_to_translate:
                    t = self.env['ir.translation'].search([
                        ('lang', '=', l),
                        ('type', '=', 'model'),
                        ('name', '=', 'res.company,field_to_translate')
                    ])
                    if t:
                        self.env['ir.translation'].create({
                            'lang': l,
                            'type': 'model',
                            'name': 'sale.order,field_to_translate',
                            'res_id': record.res_id,
                            'src': record.src,
                            'value': t.value,
                            'state': 'translated',
                        })

啊,我想这样做是因为我想将它们打印在不同的报告上。这些报告的语言将取决于客户 lang 字段。

简而言之,如何将res.company中的可翻译字段设置为sale.order模型中其他字段的默认值?其他语言的翻译也应该复制。我上面的建议有点麻烦

好吧,我终于在sale.order的创建方法中创建了翻译。我使用了 ir.translation 模型的自定义 translate_fields 方法来自动创建翻译,然后我使用正确的语言翻译手动更新它们的所有值。

另一方面,我在 l10n_multilang 模块中发现了这个 class,它对可能发现相同问题的其他人很有用:

class AccountChartTemplate(models.Model):
    _inherit = 'account.chart.template'

    @api.multi
    def process_translations(self, langs, in_field, in_ids, out_ids):
        """
        This method copies translations values of templates into new Accounts/Taxes/Journals for languages selected

        :param langs: List of languages to load for new records
        :param in_field: Name of the translatable field of source templates
        :param in_ids: Recordset of ids of source object
        :param out_ids: Recordset of ids of destination object

        :return: True
        """
        xlat_obj = self.env['ir.translation']
        #find the source from Account Template
        for lang in langs:
            #find the value from Translation
            value = xlat_obj._get_ids(in_ids._name + ',' + in_field, 'model', lang, in_ids.ids)
            counter = 0
            for element in in_ids.with_context(lang=None):
                if value[element.id]:
                    #copy Translation from Source to Destination object
                    xlat_obj._set_ids(
                        out_ids._name + ',' + in_field,
                        'model',
                        lang,
                        out_ids[counter].ids,
                        value[element.id],
                        element[in_field]
                    )
                else:
                    _logger.info('Language: %s. Translation from template: there is no translation available for %s!' % (lang, element[in_field]))
                counter += 1
        return True

    @api.multi
    def process_coa_translations(self):
        installed_langs = dict(self.env['res.lang'].get_installed())
        company_obj = self.env['res.company']
        for chart_template_id in self:
            langs = []
            if chart_template_id.spoken_languages:
                for lang in chart_template_id.spoken_languages.split(';'):
                    if lang not in installed_langs:
                        # the language is not installed, so we don't need to load its translations
                        continue
                    else:
                        langs.append(lang)
                if langs:
                    company_ids = company_obj.search([('chart_template_id', '=', chart_template_id.id)])
                    for company in company_ids:
                        # write account.account translations in the real COA
                        chart_template_id._process_accounts_translations(company.id, langs, 'name')
                        # copy account.tax name translations
                        chart_template_id._process_taxes_translations(company.id, langs, 'name')
                        # copy account.tax description translations
                        chart_template_id._process_taxes_translations(company.id, langs, 'description')
                        # copy account.fiscal.position translations
                        chart_template_id._process_fiscal_pos_translations(company.id, langs, 'name')
        return True

    @api.multi
    def _process_accounts_translations(self, company_id, langs, field):
        in_ids, out_ids = self._get_template_from_model(company_id, 'account.account')
        return self.process_translations(langs, field, in_ids, out_ids)

    @api.multi
    def _process_taxes_translations(self, company_id, langs, field):
        in_ids, out_ids = self._get_template_from_model(company_id, 'account.tax')
        return self.process_translations(langs, field, in_ids, out_ids)

    @api.multi
    def _process_fiscal_pos_translations(self, company_id, langs, field):
        in_ids, out_ids = self._get_template_from_model(company_id, 'account.fiscal.position')
        return self.process_translations(langs, field, in_ids, out_ids)

    def _get_template_from_model(self, company_id, model):
        out_data = self.env['ir.model.data'].search([('model', '=', model), ('name', '=like', str(company_id)+'\_%')])
        out_ids = self.env[model].search([('id', 'in', out_data.mapped('res_id'))], order='id')
        in_xml_id_names = [xml_id.partition(str(company_id) + '_')[-1] for xml_id in out_data.mapped('name')]
        in_xml_ids = self.env['ir.model.data'].search([('model', '=', model+'.template'), ('name', 'in', in_xml_id_names)])
        in_ids = self.env[model+'.template'].search([('id', 'in', in_xml_ids.mapped('res_id'))], order='id')
        return (in_ids, out_ids)