Skip to content
Advertisement

Odoo. Hide some options in field selection

I have some selection field in my model. Here example:

class MyModel(models.Model):
    _name = 'my_app.my_model'

    example_selection = fields.Selection(
        [
             ('first', 'First'),
             ('second', 'Second'),
             # etc.
        ], 
        string='My selection', 
    )

In some cases I need hide specific options in selection(or radio buttons). How I can do this properly?

Below screen from base calendar module which can more explain about my problem.

enter image description here

Thanks in advance.

Advertisement

Answer

I found the solution.

First of all we need to create custom widget for FieldSelection. Here example(path_to_your_module/static/src/js/form_widgets.js):

odoo.define('your_module.form_widgets', function (require) {
"use strict";

var core = require('web.core');
var FieldSelection = core.form_widget_registry.get('selection');

var MySelection = FieldSelection.extend({
    // add events to base events of FieldSelection
    events: _.defaults({
        // we will change of visibility on focus of field
        'focus select': 'onFocus'
    }, FieldSelection.prototype.events),
    onFocus: function() {
      if (
          // check values of fields. for example I need to check many fields
          this.field_manager.fields.name_field_1.get_value() == 'value1' &&
          this.field_manager.fields.name_field_2.get_value() == 'value2' /* && etc fields...*/   
      ) {
          // for example just hide all options. You can create any kind of logic here
          this.$el.find('option').hide();
      } 
    }
});

// register your widget
core.form_widget_registry.add('your_selection', MySelection);
});

After this you need just set your widget to field in your view like this:

<field name="example_selection" widget="your_selection"/>

If you don’t know how to include static of your module HERE example which can help you.

I hope this helps someone ;)

Advertisement