Search code examples
javascripthtmljqueryxmlodoo

Using jQuery to manipulate xml odoo elements


I've made some new modules in my Odoo and now when each form is loading I need to manipulate the created XML elements according to its required model and my arbitrary changes or refer to some specific function for its data validation (I know there are other ways for data validation but I'm curious if it's possible to be done with jquery functions).

I've tried to add an HTML file in the view folder and write a simple script, to begin with, but I'm not sure if it's the right place or even the right piece of code.

<script>
    $(document).ready(function()
    {  
        $("input").keyup(function(event){
            console.log('t');
        });
    });
</script>

I would be glad if anyone could offer some useful answers to my question.


Solution

  • You can customize an existing form view using the js_class attribute, its value will be the name of an extended form view.

    To bind a new event to an input, you can customize the form controller and extend the events mapping.

    Example:

    1) Extend the form view:

    odoo.define("MODULE_NAME.custom_form", function (require) {
        "use strict";
    
        var FormController = require('web.FormController');
        var FormView = require('web.FormView');
        var viewRegistry = require('web.view_registry');
    
        var CustomController = FormController.extend({
    
            events: _.extend({}, FormController.prototype.events, {
                'keyup input': '_onInputKeyup',
            }),
    
            _onInputKeyup(ev) {
                console.log('t');
            },
    
        });
    
        var CustomFormView = FormView.extend({
            config: _.extend({}, FormView.prototype.config, {
                Controller: CustomController,
            }),
        });
    
        viewRegistry.add('custom_form', CustomFormView);
    
        return {
            CustomController: CustomController,
            CustomFormView: CustomFormView,
        };
    
    });
    

    2) Add it to the assets entry in the manifest file

    'assets': {
        'web.assets_backend': [
            'MODULE_NAME/static/src/js/custom_form_view.js'
        ],
    },
    

    3) Set the js_class attribute on the form view tag

    <form js_class="custom_form">