Search code examples
odooodoo-13

Odoo13: How to assign followers to a record via Controller


In my webform controller, I am attempting to assign email addresses entered in a webform to a given record. This is the snippet of code in my controller responsible for that

if 'followers' in request.params:
            raw_emails = request.httprequest.form.get('followers').split(',')
            emails = [user.strip() for user in raw_emails] 
            #emails = ['[email protected]', '[email protected]',..]

            for email in emails:
                follower = request.env['res.users'].search(
                    [('email', '=', email)])
                if bool(follower):
                    reg = {
                        'res_id': new_ticket.id,
                        'res_model': 'helpdesk.ticket',
                        'partner_id': follower.id
                    }
                    request.env['mail.followers'].create(reg)
                else:
                    message = "TO DO: Add {} to the system and make the user a follower of this ticket".format(
                        email)
                    new_ticket.message_post(body=message)

With this I get strange results i.e after entering "user A" as a follower on the webform, "user B" gets added as a follower. I'm thinking the problem might be from the wrong user record being loaded into the follower variable but I'm not seeing why. Any feedback would be really appreciated.


Solution

  • You can use the message_subscribe method to add followers to a record set.

    def message_subscribe(self, partner_ids=None, channel_ids=None, subtype_ids=None):
        """ Main public API to add followers to a record set. Its main purpose is
        to perform access rights checks before calling _message_subscribe. """

    You have already an example in the account move, in message_new method that add a list of partners.

    # Assign followers.
    all_followers_ids = set(partner.id for partner in followers + senders + partners if is_internal_partner(partner))
    move.message_subscribe(list(all_followers_ids))