Im trying to implement post request with htmx and for rich text editor using tinymce.
my form :
<!--<form method="POST"> {% csrf_token %}--> <form onsubmit='copyContent()' method= "post" hx-post= "{% url 'forum:forum-detail' post.pk %}" hx-swap="innerHTML" hx-target = "#comment-list"> <div class="modal-body"> <div class="form-group"> <label for="threadTitle">Your Answer</label> <textarea name="reply" class="form-control summernote" placeholder="Input your answer here"></textarea> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-light" id="cancelForm">Cancel</button> <button type="submit" class="btn btn-primary" name="btn-post-question">Post</button> </div> </form>
The error I get :
<ul class="errorlist"><li>reply<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
it works just ok when I used the traditional post request with TinyMCE.
when I used htmx without TinyMCE its work just fine too.
it just when I combine htmx and TinyMCE I get the error.
my tinymce init:
tinymce.init({ selector: 'textarea', body_id : "reply", height: 200, plugins: 'a11ychecker advcode casechange export formatpainter linkchecker autolink lists checklist media mediaembed pageembed permanentpen powerpaste table advtable tinycomments tinymcespellchecker image code', toolbar: 'a11ycheck addcomment showcomments casechange checklist code export formatpainter pageembed permanentpen table image', toolbar_mode: 'floating', tinycomments_mode: 'embedded', tinycomments_author: 'Author name', });
Advertisement
Answer
Here is what solved this particular issue for me.
In this case the tinyMCE.triggerSave() method was not being triggered when the HTMX event fires. So what you need to do is call the method during one of your HTMX pre-request events. In this case I used htmx:configRequest event, however there may be better HTMX events to use.
Example:
document.body.addEventListener('htmx:configRequest', (event) => { // trigger the rich text editor save method tinyMCE.triggerSave(); // update the parameter in request richContent = document.querySelector('#{{ your form field id}}'); event.detail.parameters['{{ your form field name }}'] = richContent.value; })
Because of the way the HTMX events fire, the form values have already been collected once the htmx:configRequest event fires, so you need to update the fields value in the request. There maybe some better ways of doing this, but this is working for me.