I have a Many2many field x_studio_many2many_field_Cv65K in the project.task model, linked to hr.employee. This field allows selecting employees as "Performers" for a task. I want these selected employees to be automatically added as followers of the task when the field is updated, and the task is saved.
I tried the following code, which successfully adds employees as followers, but no notification emails are sent:
new_followers = self.x_studio_many2many_field_Cv65K.mapped(
'user_id.partner_id'
).filtered(
lambda x: x.id not in self.message_partner_ids.ids
).ids
vals = [{
'res_id': self.id,
'res_model': 'project.task',
'partner_id': pid,
} for pid in new_followers]
self.env['mail.followers'].create(vals)
How can I ensure that the followers are added and that notification emails are sent to them? Any suggestions on the correct approach or methods to achieve this would be greatly appreciated!
This solution leverages Odoo's built-in functionality by using the mail.wizard.invite
model, which is designed to handle both adding followers and sending email notifications smoothly.
Instead of directly creating records in the mail.followers model, which bypasses Odoo's notification mechanism, this method ensures that the in-built process is followed. By calling the add_followers()
function on the mail.wizard.invite
record, Odoo automatically handles all the necessary conditions, including notifying users via email invitations.
@api.constrains('x_studio_many2many_field_Cv65K')
def _constrains_performers(self):
wizard = self.env['mail.wizard.invite'].sudo().create({
'partner_ids': self.x_studio_many2many_field_Cv65K.mapped(
'user_id.partner_id'),
'send_mail': True,
'res_id': self.id,
'res_model': self._name
})
wizard.add_followers()