2
votes

I need to copy many2many field content to another class' many2many field.

 @api.multi
 def tester(self):
    context = self._context.copy()
    list = []
    confs = self.risque.rubrique_ids
    for rec in confs:
        list.append(rec.id)
    self.env['test.test'].create({
        'nom_risque': self.risque.nom_risque,
        'rubrique_ids': [0, 0, list]
    })

    return {
        'name': 'Evaluation',
        'view_type': 'form',
        'view_mode': 'tree,form',
        # 'views': [{'view_mode': 'form', 'view_id': 'rub_id'}],
        'res_model': 'test.test',
        'type': 'ir.actions.act_window',
        'res_id': self.id,
        # 'target': 'new',
        'flags': {'initial_mode': 'edit'},
        'context': context,
    }

My XML code:

  <button name="tester" string="Evaluer" type="object" class="oe_highlight" />

But it returns the nom_risque and for the rubrique_ids only the last one.

1

1 Answers

1
votes

Hi try out the following and please try to understand my comments, too :-)

@api.multi
# even if it's trying out something, give it an understandable name
def tester(self):
    # seems to be a singleton call, so restrict it with self.ensure_one()
    # no need to copy the context here, just pass it in the end
    context = self._context.copy()
    # odoo's recordsets has some cool functions, e.g. mapped()
    # but that's only usefull on other scenarios
    list = []
    confs = self.risque.rubrique_ids
    for rec in confs:
        list.append(rec.id)
    # you will call this new record later so don't forget to 'save' it
    self.env['test.test'].create({
        'nom_risque': self.risque.nom_risque,
        # that's just plain wrong, read the __doc__ on models.BaseModel.write()
        'rubrique_ids': [0, 0, list]
    })

    return {
        'name': 'Evaluation',
        'view_type': 'form',
        'view_mode': 'tree,form',
        # 'views': [{'view_mode': 'form', 'view_id': 'rub_id'}],
        'res_model': 'test.test',
        'type': 'ir.actions.act_window',
        # here is the mistake: take the id of your created record above
        'res_id': self.id,
        # 'target': 'new',
        'flags': {'initial_mode': 'edit'},
        'context': context,
    }

And now the hopefully working example:

@api.multi
def create_test_record(self):
    self.ensure_one()
    test = self.env['test.test'].create({
        'nom_risque': self.risque.nom_risque,
        'rubrique_ids': [(6, 0, self.risque.rubrique_ids.ids)]
    })

    return {
        'name': 'Evaluation',
        'view_type': 'form',
        'view_mode': 'tree,form',
        'res_model': 'test.test',
        'type': 'ir.actions.act_window',
        'res_id': test.id,
        'flags': {'initial_mode': 'edit'},
        'context': self.env.context
    }