How to add a background color on tags using many2many_tags widget

When using many2many_tags​ widget, it is possible to define a background color for each of the tag values. For that to work the following steps need to be done:

  • The related model needs to have an Integer type field where the color index will be stored, usually named color​.
  • The color​ field needs to be added in the view using the widget color_picker
  • In the definition of the relational field in the XML view, when using the widget many2many_tags​, it needs to be set the option color_field​ with value the name of the color field previously defined.​
  • The last step is optional, by default when a user selects a value, can edit the background color of the value's tag, however, it is possible to make the color not editable at this stage, by using the option no_edit_color

Let’s review the steps above using as an example the relational many2many​ field tag_ids in the sale.order​ model related to the relational model crm.tag​​.

The model crm.tag​ there is a field color​ defined in the model definition as the following:

color = fields.Integer("Color")

The definition of the field in the XML view, using the widget color_picker​ looks like the following:

<field name="color" required="True" widget="color_picker"/>

Having this definition of the field makes it possible for every sales tag value defined in the system to be selected a color which later will be used as a background color for the tag.

Once the field is set up in the relational model the next step is when defining the related field tag_ids​ in the XML views to use the widget many2many_tags​ and add as an option the color_field​.

<field name="tag_ids" widget="many2many_tags" options="{'color_field': 'color'}"/>

This will add a background color for the selected tag values in the sales order. Also users will be able to change the color of the tags during the selection process. A possible issue with this change is that the color will be applied to all sales orders where the same value is used. In case the admin wants to keep the colors same as initially set, it is possible to disable the edit of the color at the moment of selection by using the option no_edit_color​ set to True​.

<field name="tag_ids" widget="many2many_tags" options="{'color_field': 'color', 'no_edit_color': true}"/>