Search code examples
pythonodooodoo-12

how to fill field automatically in custom view from another field in another view in Odoo?


I want to create clearance for a contract with some items with 3 attributes of every item I have 4 models:

  1. Contract

  2. Clearance

  3. item
  4. Clearance_item_rel

When I'm in the custom view of clearance model I select a contract from Many2one relation field

then try to create a Clearance_item_rel record in the Clearance_item_rel model.

When I click to create a Clearance_item_rel record it opens the custom view in a new window

I want to use the selected contract id in the first view to fill the contract_id field in Clearance_item_rel automatically as the user has just selected it in the first view

P.S: clearance_id is created automatically as I create the Clearance_item_rel record from clearance custom view But contract_id doesn't do and this's my problem

Contract:

class Contract(models.Model):
    _name = 'clearance.contract'
    clearances = fields.One2many('clearance.clearance_item_rel', 
    'contract_id')

clearance:

class Clearance(models.Model):
    _name = 'clearance.clearance'
    contract = fields.Many2one('clearance.contract','Contract')
    items = fields.One2many('clearance.clearance_item_rel',clearance_id')

Clearance_item_rel:

class Clearance_item_rel(models.Model):
    _name = 'clearance.clearance_item_rel'
    contract_id = fields.Many2one('clearance.contract', 'Contract', ondelete='cascade')
    clearance_id = fields.Many2one('clearance.clearance', 'Clearance', ondelete='cascade')
    item_id = fields.Many2one('clearance.contract_item_rel', 'Item', ondelete='cascade')
    previous_quantity = fields.Integer()
    used_quantity = fields.Integer()
    total_price = fields.Integer()

Solution

  • Answer

    You can do it via context on the field definition of the form view. Sample code:

    <record id="clearance_view_form" model="ir.ui.view">
        <field name="name">clearance.view.form</field>
        <field name="model">clearance.clearance</field>
        <field name="arch" type="xml">
            <form>
                <field name="contract"/>
                <field name="items" context={'default_contract_id': contract}/>
            </form>
        </field>
    </record>
    

    Where default_contract_id is the field name of clearance.clearance_item_rel prefixed with default_ and contract is the value you want to fill the field with (in this case, the field name on clearance.clearance model). Note that default_contract_id uses quotes, while contract does not.

    Tips

    Some other tips you might want to consider, as I see your code does not follow some Odoo naming conventions:

    • M2o field names should be suffixed with _id as in contract_id
    • O2m and M2m fields should be suffixed with _ids as in item_ids or clearance_ids