Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odoo custom form field widget - how to display field value?

I've created a custom widget in Odoo, and display it for a form field. My template looks like this:

<t t-name="ImageDisplayer">
    <img t-att-src="?"/>
</t>

How can I put the field's value into the <img> tag's src attribute?

like image 805
Aron Lorincz Avatar asked Aug 13 '15 14:08

Aron Lorincz


Video Answer


1 Answers

After spending a day digging in the source code, I've found the solution! It doesn't really involve the template, but I got the idea from the source code of default text field widget, so I think it shouldn't be considered as "hacking".

Here's my custom widget class:

openerp.mymodule = function(instance, local) {
    instance.ImageDisplayer = instance.web.form.AbstractField.extend({
        template: "ImageDisplayer",
        init: function (view, code) {
            this._super(view, code);
        },
        // The key part:
        render_value: function() {
            this.$el[0].src = this.get("value");
        }
    });
    instance.web.form.widgets.add('ImageDisplayer', 'instance.ImageDisplayer');
}

My template now does not contain anything special:

<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
    <t t-name="ImageDisplayer">
        <img />
    </t>
</templates>

Works like a charm. It even updates the page whenever I do a change on server-side.

Odoo documentation should really be more talkative!!!

Update: the answer applies to Odoo 8. It may work slightly differently in Odoo 9, because they've revised the UI framework in the new version.

like image 64
Aron Lorincz Avatar answered Oct 08 '22 06:10

Aron Lorincz