Search code examples
pythonpython-3.xodooodoo-10odoo-11

How to update any view from python code, before rendering completion, in Odoo?


I have a problem with passing value for colors argument in my view element. So i have my model which has a function to return colors:

class MyTask(models.Model):
     _inherit = "project.task"
     is_special=fields.Boolean()     

     @api.model
     def get_colors(self):
          return 'red: is_special == true;'

And I also have got my view which looks like this:

<record id="my_module_timeline" model="ir.ui.view">
<field name="model">project.task</field>
<field name="type">timeline</field>
<field name="arch" type="xml">
    <timeline date_start="date_start"
            date_stop="date_end"
            default_group_by="project_id"
            event_open_popup="true"
            colors= <-- how can i get the value from my model get_colors() function?
            >
    </timeline>
</field>

colors argument has to be string, and it cannot be a field of model. I tried a lot options to get this string from model function, but without good results.

<timeline> element is just example it can be also tree, calendar etc. For tests i got it from:

https://github.com/OCA/web/tree/11.0/web_timeline

It is possible in this way?

Thank you.


Solution

  • You can use the fields_view_get method to update the view dynamically from python code (before the view is rendered). This is just an example that I found in Odoo:

    @api.model
    def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
        res = super(MailThread, self).fields_view_get(
            view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu
        )
        if view_type == 'form':
            doc = etree.XML(res['arch'])
            for node in doc.xpath("//field[@name='message_ids']"):
                # the 'Log a note' button is employee only
                options = safe_eval(node.get('options', '{}'))
                is_employee = self.env.user.has_group('base.group_user')
                options['display_log_button'] = is_employee
                # save options on the node
                node.set('options', repr(options))
            res['arch'] = etree.tostring(doc, encoding='unicode')
        return res
    

    Place it in your model. Look for the node with doc.xpath and update it with node.set