I'm trying to wrap my head around how this actually works in wordpress on the admin back end for a widget I'm trying to create (similar to the custom HTML widget). I've read a few tutorials but the information seems to change and I feel I have just confused myself.
Everything works fine while initializing codemirror and it is applied to the textarea but the errors I'm having are:
If I change another field to activate the save button the data from codemirror is not sent or saved.
(function ($) {
$(document).ready( function(){
var editorSettings = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {};
editorSettings.codemirror = _.extend(
{},
editorSettings.codemirror,
{
lineNumbers: true,
mode: "text/html",
indentUnit: 2,
tabSize: 2,
autoRefresh:true,
}
);
var editor = wp.codeEditor.initialize( $('#<?php echo $textarea_id; ?>'), editorSettings );
});
})(jQuery);
</script>
I've also tried adding:
$(document).on('keyup', '.CodeMirror-code', function(){
editor.codemirror.save();
$('#<?php echo $textarea_id; ?>').html(editor.codemirror.getValue());
});
but editor.codemirror.getValue() return empty when I display through console.log
Code for Textarea
<p>
<label for="<?php echo $textarea_id; ?>"><?php _e( 'Locked Content:' ); ?></label>
<textarea id="<?php echo $textarea_id; ?>" name="<?php echo $this->get_field_name( 'locked-content' ); ?>" class="widefat"><?php echo esc_textarea( $instance['locked-content'] ); ?></textarea>
</p>
Any help (links to a proper tutorial, advice etc) would be much appreciated JS isn't my strongest language.
I believe this came down to me being an idiot lol I was calling this same block of code from another widget as I was trying to make both widgets textareas into codemirrors.
I changed the name of 2 variables to be more specific towards the widget eg:
var editorSettings
var editor
where changed to:
var cm_editorSettings
var cm_editor
This allowed me to us cm.editor.codemirror.getValue() and return the actual value. Still not sure if this is the correct way to implement it so please correct me if I am wrong but currently the working code to update the textarea and enable save button is as follows
<script type="text/javascript">
(function ($) {
$(document).ready( function(){
var cm_editorSettings = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {};
cm_editorSettings.codemirror = _.extend(
{},
cm_editorSettings.codemirror,
{
lineNumbers: true,
mode: "text/html",
indentUnit: 2,
tabSize: 2,
autoRefresh:true,
}
);
var cm_editor = wp.codeEditor.initialize($('#<?php echo $textarea_id; ?>') , cm_editorSettings );
$(document).on('keyup', '.CodeMirror-code', function(){
$('#<?php echo $textarea_id; ?>').html(cm_editor.codemirror.getValue());
$('#<?php echo $textarea_id; ?>').trigger('change');
});
});
})(jQuery);