在更改 odoo 9 时填充 select 选项

Populate select option on change odoo 9

如何在更改其他字段时填充 select 选项。例如:

select 选项的默认值存储在数据库 tbl_car(奥迪、欧宝、梅赛德斯、大众、宝马)中。在其他 table tbl_car_user 我存储 car_name 和 user_name ('Peter','Audi')。现在我想在汽车 select 选项中更改 user_id (Select 用户彼得)选项得到所有汽车不包括奥迪(用户彼得已经使用奥迪)。

可能是这样的:

for car in self.env['tbl.car'].search([]):
    for car_user in self.env['car.user'].search([('user_id','=','self.user_id.id]):
    if (car.name = car_user.name):
       print("DUPLICATE")
    else:
       print("ADD TO SELECT OPTION")

有什么简单的解决办法吗?

这种问题不要使用 Selection,即使你发现了这个,如果你下次编辑记录,selection 将不知道它包含的值,因为 odoo 会用除 value 之外的所有值填充 selection它有。您将在选择字段中看到未知值。

但如果你想这样做,请不要使用选择,使用 many2one 将汽车名称的选择更改为模型(table 在数据库中)并为你使用域 many2one 字段。

您不能通过选择来执行此逻辑此逻辑只能通过选择来完成向导。

field_selection = fields.Selection(selection='generate_selection')

def generate_selection(self):
    # compute selection
    return computed_selection

但这在第一次加载视图时有效,现在无法使用 onchange 事件编辑或更改选择的值。

我的第一个答案是正确的,如果你不想改变选择,我会给出一个解决方案:

创建一个向导来影响用户的汽车:

class AffectCar(model.TransientModel):
    _name = 'affect.user.car.wizard'
    use_id = fields.Many2one(..) # you know how you do it
    car_name = fields.Selection(selection='_get_car_selection', 'Car name')

    def _get_car_selection(self):
     """
       generate a selection for field car_name according to
       the default user_id passed to this form
     """
     # get all car name that this user don't have 
     # generate the selection [('car_name','car_name')..]
     return computed_selection

   def create_user_car(self):
    """ save a new tbbl_car_user record  """
    # this method is called from the form of the wizard
    # save the user_id and the car_name in tbl_car_user 

现在添加一个按钮到用户窗体并调用一个方法来打开向导窗体 user_id 默认是 同一用户

@api.multi()
def add_car(self):
    """
      open the wizard to add a car
      to this user 
    """
    return {
        'type': 'ir.actions.act_window',
        'view_mode': 'form',
        'view_type': 'form',
        'res_model':'affect.user.car.wizard',
        'target': 'new', 
        'context': {
             # pass the id the the user to the wizard
            'default_use_id': self.id,
        },
        }

防止您的应用程序用户在显示弹出窗口时更改 user_id 的一件事 使用户在向导的窗体视图中 invisble="1"

<record id="add_car_wizard" model="ir.ui.view">
    <field name="name">tax.adjustments.wizard.form</field>
    <field name="model">tax.adjustments.wizard</field>
    <field name="arch" type="xml">
    <form>
        <group>
            <field name="user_id" invisible="1"/>
            <field name="car_name"/>
        </group>
        <footer>
            <button name="create_user_car" string="Add car" type="object" class="oe_highlight"/>
            or 
            <button string="Cancel" special="cancel" />
        </footer>
    </form>
    </field>
</record>