Enable Dark Mode!
how-to-add-chatter-followers-and-message-posting-to-custom-models-in-odoo-20.jpg
By: Ayana R

How to Add Chatter, Followers and Message Posting to Custom Models in Odoo 20

Technical Odoo 20 Odoo Community Odoo Enterprises

Chatter is a functionality provided by Odoo where one can discuss records, attach files, change fields, and manage followers.

While developing a custom module, the developer can make use of the above-discussed features with models. Odoo provides reusable mixins – mail.thread and mail.activity.mixin for developers; therefore, there is no need for a separate messaging system to be developed.

In this blog, the information about using Chatter with a custom model in Odoo 20, follower management, sending messages programmatically, attachments, and field modification will be discussed. There will be two specific mixins – mail.thread.subject.suggested and mail.thread.main.attachment considered.

1. Create a Custom Module

We will do this through the creation of a model called service.request, which stores information about customer service requests.

The model has to depend on the mail module since the communications and activities features are created here.

How to Add Chatter, Followers and Message Posting to Custom Models in Odoo 20-cybrosys

Manifest file (__manifest__.py):

{
    'name': 'Service Request Management',
    'version': '20.0.1.0.0',
    'depends': ['base', 'mail'],
    'data': [
        'security/ir.access.csv',
        'views/service_request_views.xml',
    ],
    'installable': True,
    'application': True,
}

2. Add Chatter and Activity Support Using Mixins

Odoo has two mixins that are commonly used in order to implement functionalities of communication and activities in custom models.

  • Mail.Thread: Provides functionalities such as messaging, followers, message logging, and tracking fields.
  • Mail.Activity.Mixin: Provides functionalities such as planned activities like calls, meetings, and reminders.

Both mixins can be extended in a custom model.

Python file (models/service_request.py):

from odoo import models, fields

class ServiceRequest(models.Model):
    _name = 'service.request'
    _description = 'Service Request'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    name = fields.Char(
        string='Request Reference',
        required=True,
        tracking=True
    )
    partner_id = fields.Many2one(
        'res.partner',
        string='Customer',
        tracking=True
    )
    description = fields.Text(string='Description')
    state = fields.Selection([
        ('draft', 'Draft'),
        ('in_progress', 'In Progress'),
        ('done', 'Done'),
    ], string='Status', default='draft', tracking=True)

In the current example, inheritance extends the custom model using the properties provided by the two mixins.

Inheriting from the mail.thread will provide the messaging capability that is needed for the Chatter. The inheritance from the mail.activity.mixin provides the activity capability.

The tracking=True attribute on some fields will enable the tracking of field changes in the Chatter.

3. Add the Chatter Widget to the Form View

Once we add the mixins, we will proceed with displaying the chatter in the form view of the newly created model.

In Odoo 20, there is a tag named <chatter/> that is used for displaying the chatter widget. It has replaced the earlier method in which we used oe_chatter and its fields.

XML file (views/service_request_views.xml):

<odoo>
    <record id="view_service_request_form" model="ir.ui.view">
        <field name="name">service.request.form</field>
        <field name="model">service.request</field>
        <field name="arch" type="xml">
            <form string="Service Request">
                <sheet>
                    <group>
                        <field name="name"/>
                        <field name="partner_id"/>
                        <field name="state"/>
                        <field name="description"/>
                    </group>
                </sheet>
                <chatter/>
            </form>
        </field>
    </record>
</odoo>

<chatter/> The element shows the messaging popup in the form view. Posting messages, taking internal notes, managing followers, scheduling, and uploading attachments can all be done using this element.

There are other features too:

  • open_attachments: Automatically opens in the attachment section.
  • reload_on_attachment: Reloads the form if there are any changes in attachments.
  • reload_on_follower: Reloads the form if there are any changes in followers.
  • reload_on_post: Reloads the form if a new message is posted.

Example:

<chatter
    open_attachments="True"
    reload_on_follower="True"
    reload_on_post="True"
/>

Form for Service Request containing the Chatter interface

How to Add Chatter, Followers and Message Posting to Custom Models in Odoo 20-cybrosys

4. Post Messages Programmatically Using message_post()

In addition to providing a mechanism for sending messages manually using the Chatter module, Odoo also offers another functionality known as message_post() that generates messages.

This function is useful when there is a need for automatic generation of messages following a certain event in business, like request approval, status change, or allocation to an employee.

Example:

def action_start_request(self):
    for record in self:
        record.state = 'in_progress'
        record.message_post(
            body='The service request has been started.',
            message_type='comment',
            subtype_xmlid='mail.mt_comment',
        )

In this example, upon running the function, the request status is marked as “In Progress,” and the message is published on the Chatter for it.

Parameters that may be passed in the message_post() function are as follows:

Important Parameters of message_post()

1. body

This parameter is used to decide on the message content.

record.message_post(
    body='The service request has been completed.'
)

HTML tag formatting in text requires the use of markupsafe.Markup. The reason for this is that Odoo escapes all non-significant strings.

from markupsafe import Markup
record.message_post(
    body=Markup('<p><strong>Service request completed.</strong></p>')
)

2. subtype_xmlid

The subtype_xmlid field decides what type of message/notification it belongs to. Typically there are two types of subtypes, which are as follows:

  • mail.mt_comment: This one is for any other general message type. The followers of this subtype will get notifications for this particular message.
  • mail.mt_note: This one is for internal notes.
record.message_post(
    body='The request requires additional verification.',
    subtype_xmlid='mail.mt_note',
)

3. partner_ids

"Partner_ids" is the field for other partners who must be notified of the message.

The "partner_ids" field is made up of a set of records of "res.partner ID".

record.message_post(
    body='A new service request has been assigned to you.',
    partner_ids=[partner.id],
    subtype_xmlid='mail.mt_comment',
)

These users will get notified despite the fact that they have not followed the record yet.

4. attachments

The attachments parameter is an optional parameter where you can attach certain files along with your message.

In the list of attachments, there will be a pair of filename and file content, and the file content does not have to be in Base64 format.

record.message_post(
    body='Please refer to the attached service report.',
    attachments=[
        ('service_report.txt', b'Service request report content')
    ],
    subtype_xmlid='mail.mt_comment',
)

If there is an attachment, then use “attachment_ids” instead of “attachment_files” and specify the IDs of the attachments.

Combining Parameters:

The below example is of combining all the above parameters.

record.message_post(
    body='The service request has been assigned.',
    subtype_xmlid='mail.mt_comment',
    partner_ids=[partner.id],
    attachments=[
        ('service_report.txt', b'Service report details')
    ],
)

This will result in a posting on the record chatter and inform the specified partner and attach the required file.

Post generated programmatically within Chatter with Attachment

How to Add Chatter, Followers and Message Posting to Custom Models in Odoo 20-cybrosys

5. Manage Followers Using message_subscribe()

A follower is a partner that follows a certain document to get notified of any message added to the document.

The message subscribe method is used in the Odoo Framework to create a follower.

Example:

def action_add_follower(self):
    for record in self:
        partner = record.partner_id
        if partner:
            record.message_subscribe(
                partner_ids=[partner.id]
            )

The follower in this scenario will be the customer of the service request.

For partner_ids, a list of partner_ids needs to be passed. What is very important to remember is that the user should not pass res.users ids, but res.partner ids.

This method can have subtype_ids also.

record.message_subscribe(
    partner_ids=[partner.id],
    subtype_ids=[subtype.id]
)

Odoo will use default subscription subtypes when subtype_ids are not provided.

How to Add Chatter, Followers and Message Posting to Custom Models in Odoo 20-cybrosys

6. Track Field Changes Using the tracking Attribute

Odoo has an inbuilt system which can assist in tracking through mail.thread. This will be helpful in tracking any changes in the mentioned fields and then showing the same in Chatter.

This is done by including tracking=True in the field. Example:

name = fields.Char(
    string='Request Reference',
    tracking=True
)
partner_id = fields.Many2one(
    'res.partner',
    string='Customer',
    tracking=True
)
state = fields.Selection([
    ('draft', 'Draft'),
    ('in_progress', 'In Progress'),
    ('done', 'Done'),
], default='draft', tracking=True)

If any of the tracked fields is changed, Odoo will generate the tracking message in the Chatter with both the old and new values of that field.

The tracking property can be set to an integer as well. It denotes the priority of the tracked fields in the tracking message.

Example:

name = fields.Char(tracking=1)
partner_id = fields.Many2one('res.partner', tracking=2)
state = fields.Selection(
    [('draft', 'Draft'), ('done', 'Done')],
    tracking=3
)

7. Specialized Mail Thread Mixins in Odoo 20

Apart from the common mixin mail.thread, Odoo version 20 also contains specialized forms of mail thread mixins to achieve extra functionality.

Some of them are mail.thread.subject.suggested and mail.thread.main.attachment.

7.1 mail.thread.subject.suggested

The inclusion of subject proposals in thread messages is taken care of through the use of the mixin.

It performs effectively for business documents whereby the messaging is focused on a specific record, thereby improving the efficiency of communication through the use of subject proposals.

One example of such a document is the document in Odoo 20.

from odoo import models, fields

class ServiceRequest(models.Model):
    _name = 'service.request'
    _description = 'Service Request'
    _inherit = [
        'mail.thread.subject.suggested',
        'mail.activity.mixin',
    ]
    name = fields.Char(
        string='Request Reference',
        tracking=True
    )

This can be another method of applying the mixin, rather than inheritance of mail.thread, in case you want to have the capability of suggesting the subject line automatically.

The mixin will build upon the functionalities provided by the existing mail thread.

It is not essential to apply the mixin in all cases where chatter is required on custom models.

7.2 mail.thread.main.attachment

It adds another functionality to the mail thread by providing an additional capability of managing the main attachment of the record.

There is a new field ‘message_main_attachment_id’ added that links the record to its main attachment.

In the case of service requests, there can be a main document like a Service Report.

from odoo import models, fields

class ServiceRequest(models.Model):
    _name = 'service.request'
    _description = 'Service Request'
    _inherit = [
        'mail.thread.main.attachment',
        'mail.activity.mixin',
    ]
    name = fields.Char(
        string='Request Reference',
        tracking=True
    )

The use of the message_main_attachment_id message field allows getting or setting the main attachment.

For instance, after adding an attachment to the service request:

attachment = self.env['ir.attachment'].create({
    'name': 'Service Report.pdf',
    'type': 'binary',
    'datas': file_content,
    'res_model': record._name,
    'res_id': record.id,
})
record.message_main_attachment_id = attachment.id

For instance, in ir.attachment, the file_content is represented by the Base64 encoding of the content of the ir.attachment.datas field.

This Mixin may prove useful in case there is only one primary attachment that needs to be attached to the business document, as well as the attachments that work with chatter.

Note: The following are some of the special Mixins that offer extended functionalities to mail.thread. Select the inheritance type depending on the model you need.

The integration of Chatter into a custom model in Odoo 20 allows for increased communication and documentation of business processes. Using inheritances like mail.thread and mail.activity.mixin enables the developer to include functionalities such as messaging, followers, tracking, and activity in a custom module without having to code the functionalities.

Functions like message_post() and message_subscribe() allow better control over the programmatic communication process, while the tracking parameter ensures the automatic documentation of any changes to a field.

The functionalities of Mail.thread.subject.suggested and mail.thread.main.attachment mixins rely on the above functionalities in suggesting a subject for a message and main attachments of a model, respectively.

To read more about How to Post a Message to Chatter in Odoo 19, refer to our blog How to Post a Message to Chatter in Odoo 19.


Frequently Asked Questions

How to make Chatter work on a custom model in Odoo 20?

For Chatter functionality in your custom model, you need to inherit mail.thread in your custom model and include it in your custom form view definition. To use Activity Scheduler in your custom module, you need to inherit mail.activity.mixin in your custom model.

What is the difference between message_post() and message_subscribe() in Odoo 20?

message_post() is used to post messages in the Chatter of a record, whereas message_subscribe() is used for following.

How to track the changes in fields in Odoo 20?

Use tracking=True in the fields of your custom model, which has been inherited from mail.thread and which you want to track.

If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



WhatsApp