Removing items from an Existing Selection in Odoo

Question:

I have pre-existing keys in a selection in a contact form. I added new keys using “selection_add” parameter and I wanted to find out what would be the opposite of a selection_add parameter to remove any old keys from a selection.

Asked By: Jeff Nyak

||

Answers:

There isn’t any selection_remove option, unfortunately. You could redefine the field’s selection value entirely, removing the option(s) you don’t want.

If a field is defined with:

class ResPartner(models.Model):
    _name = 'res.partner'

    some_field = fields.Selection(string='Some Field',
                                  selection=[('a', 'A'),  ('b', 'B'), ('c', 'C')])

Then you can inherit the class and override the field’s selection value

class ResPartner(models.Model):
    _inherit = 'res.partner'

    some_field = fields.Selection(selection=[('a', 'A'),  ('b', 'B')])

Odoo Fields Documentation

Answered By: travisw

To remove options from an odoo 15 selection field, proceed as follows:

Example:

Basic model

class SurveyQuestion(models.Model):
    _name = 'survey.question'

    question_type = fields.Selection([
    ('text_box', 'Multiple Lines Text Box'),
    ('char_box', 'Single Line Text Box'),
    ('numerical_box', 'Numerical Value'),
    ('date', 'Date'),
    ('datetime', 'Datetime'),
    ('simple_choice', 'Multiple choice: only one answer'),
    ('multiple_choice', 'Multiple choice: multiple answers allowed'),
    ('matrix', 'Matrix')], string='Question Type',
    compute='_compute_question_type', readonly=False, store=True)

Inheritance model

class SurveyQuestionInherited(models.Model):
    _inherit = 'survey.question'

    question_type = fields.Selection(selection='_get_new_question_type', string='Type de question',
                                 compute='_compute_question_type', readonly=False, store=True)

    @api.model
    def _get_new_question_type(self):
    """Cette methode permet de mettre à jour les types de question,
       Dans le but de retirer les options 'multiple_choice' et 'matrix'
    """
        selection = [
        ('text_box', 'Zone de texte à plusieurs lignes'),
        ('char_box', 'Zone de texte sur une seule ligne'),
        ('numerical_box', 'Valeur numérique'),
        ('date', 'Date'),
        ('datetime', 'Date et heure'),
        ('simple_choice', 'Choix multiple : une seule réponse')
        ]
        return selection

After several unsuccessful attempts, this method worked for me.

I really hope it helps !