Skip to Content
Menú
This question has been flagged

I have a model Team which has its members stored in a o2m field:

class Team(models.Model):
​_name = 'example.team'

​member_ids = fields.One2many(
​comodel_name = 'example.member',
​inverse_name = 'team_id'
)


Team members are represented by their respective model:

class Member(models.Model):
​_name = 'example.member'

​team_id = fields.Many2one('example.team', required = True, ondelete = 'cascade')
​contact_id = fields.Many2one('res.partner', required = True, ondelete = 'cascade')
​membership_fee = fields.Float()
​[...]

        

Now, I want to create a new Team from within an action by opening a Team form view with some of its values pre-filled, including some members:

class Other(models.Model):
​_name = 'example.other'

​def action_create_team(self):
​# Select some contacts which shall be added as members to the new Team below
​contacts = self.env['res.partner'].search([])
​# We cannot create Members from the contacts here because we don't have a team_id yet.
​action = {
​'type':         'ir.actions.act_window',
​'res_model':    'example.team',
​'view_mode':    'form',
​'context':      {
​'default_member_ids': }
​}
​return action


The problem is that I cannot create new Members in the action which I could pass in via the context because there is no team_id yet which is needed to create Member records.

On the other hand, members can be added in the Team form view even before the Team is saved/created so I guess there must be a way...

Any help is greatly appreciated...

Avatar
Descartar
Autor Best Answer

In fact, I have found another solution in the meantime:

It is possible to provide default values to the Team record to be created via the context like so:

action = {
'type':         'ir.actions.act_window',
'res_model': 'example.team',
'view_mode':    'form',
'context':      {'default_member_ids': contacts.ids}
}

That way, one does not have to create a Team record in advance -- which has the advantage that the new Team record can still be discarded in the form view.

Avatar
Descartar
Best Answer

Hi,

Try this:def action_create_team(self):

        contacts = self.env['res.partner'].search([])

        team = self.env['example.team'].create({

        })

               for contact in contacts:

            self.env['example.member'].create({

                'team_id': team.id,

                'contact_id': contact.id,

                # Add any other default values for the Member here

            })


        # Open the form view for the new Team

        action = {

            'type': 'ir.actions.act_window',

            'res_model': 'example.team',

            'view_mode': 'form',

            'res_id': team.id,

            'context': self.env.context,

        }

        return action


Hope it helps

Avatar
Descartar
Related Posts Respostes Vistes Activitat
1
de set. 23
1895
1
de gen. 24
1903
1
d’oct. 23
2507
0
d’ag. 23
1799
1
de des. 22
2764