Attach codemirror to w2ui textarea

I am trying to intialize codemirror inside a w2ui textarea. The textarea belongs to a form generated inside a popup. This is the code for the form:

var formConfig = {
    name: 'form_dataEdit',
    style: 'border: 0px; padding 5px',
    fields: [
        { name:'contents', type:'textarea', required: true, html:{attr:'style="width:'+width*0.7+'px;height:'+height*0.7+'px"'} },
    ],
    url: 'w2uiRecord_dataContents',
    recid: name,
    postData: {
        fileName : name
    },

    actions: {
        "Save": function () {
            w2ui.grid.lock('', true);
            $.ajax({
                url: "data_edit",
                type: "POST",
                datatype:"json",
                data: ({
                    "fileName":node.key,
                    "record" : JSON.stringify(this.record)
                }),
                success: function(response) {
                    w2ui.grid.unlock();
                    tab_objects.generate()
                }
            });
            $().w2popup('close');
            this.clear();
        }
    }
}

I have tested this code and works well. However, when I try to attach codemirror by adding the following event it does not work:

onRender: function (event) {
    event.onComplete = function () {
        console.log(this.fields[0].el) // undefined
        console.log(w2ui.form_dataEdit.fields[0].el) // undefined

        var codeMirror = CodeMirror.fromTextArea(
            this.fields[0].el,
            {
                'mode':{'name':'javascript'},
                'theme':'midnight'
            });
        codeMirror.setSize(width*0.7, height*0.7);
    }
}

I am initializing code mirror with the onRender event with onComplete so that it is called once the form has been generated, however w2ui.form_dataEdit.fields[0].el (or this.fields[0].el) is undefined. If I execute this code manually on the console once the form is generated then it works properly.

What am I missing ? How can I make sure that the form is available before calling codemirror on it ?

1 answer

  • answered 2018-10-11 21:45 Tomas Ruiz

    The problem is that onRender the form is rendered/available but not the textarea inside it. The workaround is to add an event listener to the textarea. This can be done inside the attr tag when defining the form fields as follows:

    fields: [
        { name:'contents', type:'textarea', html: {attr:'onclick="initCodemirror()"'} }
    ]
    

    Where initCodemirror() is a function initializing codemirror for in the textarea. Note that I am using onclick since onload does not seem to work.