Search code examples
pythonxmlodooodoo-13formview

Call python function in xml for set attribute of form view in odoo 13


I have a form view and I want to set the create and edit attributes to it dynamically. here is my form view record:

 <record model="ir.ui.view" id="estate_property_type_form">
            <field name="name">estate_property_type_form</field>
            <field name="model">estate.property.type</field>
            <field name="arch" type="xml">
                <form>
                    <sheet>
                           some fileds...
                    </sheet>
                </form>
            </field>
        </record>

and I used xpath tag to set create and edit attributes there but I can't call my function in estate.property.type model here is my record for set attributes : '''

<record id="changing_attrs" model="ir.ui.view">
            <field name="name">changing attrs</field>
            <field name="model">estate.property.type</field>
            <field name="inherit_id" ref="estate_property_type_form"/>
            <field name="arch" type="xml">
                <xpath expr="//form" position="attributes">
                    <attribute name="create">model_estate_property_type_form.test()</attribute>
                </xpath>
            </field>
        </record>

where in test function I do some logic and return true or false. I also tried user.env['estate.property.type'].test(), estate.property.type.test() and test() between attribute tags but it didn't work. can someone help me to call my function here or tell me another way to set form attributes dynamically?????


Solution

  • You can use fields_view_get method. replace YourClass and your_text() properly,

    @api.model
    def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
        res = super(YourClass, self).fields_view_get(
            view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu
        )
        doc = etree.XML(res['arch'])
        if view_type == 'form' and self.your_test():
            for node in doc.xpath('//{}'.format(view_type)):
                node.set('create', '0')
        res['arch'] = etree.tostring(doc, encoding='unicode')
        return res
    

    I hope this answer can be helpful for you.