Search code examples
odooodoo-10

set default value for a many2one field


when the user set nom_rubrique that come the value of many2one filled will be set by default

 class A(models.Model):

    rubrique_id = fields.Many2one('risques.rubrique',
        string='Rubrique',
        default=_default_rubrique,
        index=True,
        track_visibility='onchange',
        change_default=True)

class B(models.Model):
    critere_ids = fields.One2many('risques.critere','rubrique_id',required=True, string="Critére d'évaluation")

Solution

  • Than just in your context in the xml form or tree use this:

     <field field="id" invisible="1"/>
     <field name="critere_ids" context="{'default_rubrique_id': id}" />
    

    but this works only if the record is created and you are trying to modify it. you will see that the m2o field field will have the same record that you are in.

    but when you are in create mode the record is not created at that point so will never be able to pass it as default and the many2one will stay empty no metter what you do.

    But even fi the user select another record when the user save the parent record you will see that the selected value has changed to the parent value. what i mean no metter what the user select on that m2o field the value will be ingnored and replaced by the parent id.

    so best thing to is define a embaded tree and form for your one2many field:

    <field name="critere_ids">
         <tree>
             <!-- list of field without rubrique_id field -->
         </tree>
         <form>
            <!-- new form structor  without rubrique_id field -->
         </form>
    </field>
    

    because in one2many field the user don't need to see that many2one at all he know that the record belong to the parent so see it, or select it at all.