Search code examples
wordpresscodemirror

Wordpress CodeMirror.fromTextArea is not a function error


I am using code mirror editor from wordpress bundle in a plugin page. I have enqueued the following styles and scripts as per some research here.

wp_enqueue_style('wp-codemirror');
$cm_settings['codeEditor'] = wp_enqueue_code_editor(array('type' => 'text/css'));
$var = array(
    'cm_settings'   => $cm_settings
);
wp_localize_script('my-admin-script', 'my_var', $var);

Then in my js file, i have added the following line to make the textarea my_textarea to code editor.

 wp.codeEditor.initialize($('#my_textarea'), my_var.cm_settings);

Everything works fine. I am not able to get value from the code mirror editor. I tried

var editor = CodeMirror.fromTextArea(document.getElementById("my_textarea"));
console.log(editor.getValue());

But i am getting an error saying CodeMirror.fromTextArea is not a function. I have been stuck at this the whole day. Any helps are appreciated.


Solution

  • The issue was solved on setting a variable,

    var editor = wp.codeEditor.initialize($('#my_textarea'), my_var.cm_settings);
    

    and accessing the varibale editor, you can do anything.

    for eg: you can use editor.codemirror.getValue() to access the value. You don't need to use CodeMirror.fromTextArea here.