Using WTForms, Flask, CKEditor
I have a field in my form that has a dynamic number of entries; they can be both added and removed. Setting this up in WTForms was tricky and I utilized the solution discussed at this link. I am not well acquainted with JS so I'm finding it hard to adapt this function to produce a CKEditorField instead of a regular StringField/<textarea>.
The code below works, nothing is "broken" but the RTE doesn't show up, only a regular textarea. This led me to believe that the problem is in the HTML rather than the Flask files, but I have included both just in case.
What I have tried so far is:
(1) Replaced Entry form's bullet StringField with a CKEditorField (Forms.py, below)
(2) Adding "class=ckeditor" to the textarea return and manually calling CKEditor's replace functions (even though the docs say that this is automatically included) (app.js)
(3) Creating and returning CKEditor.config calls to the HTML for each newly generated field (the docs suggest having this for each CKE on a page, and the other places that I use CKE ((the non-dynamically-created ones)) are working with this in place) (app.js)
(4) Replacing the <textarea> return with a call to CKEditor.create (this one is where I believe the answer probably lies but it hasn't worked and I can't figure out what else to try) (app.js/webpage.html)
Also just to note, the other form field, plans, is working with the editor successfully.
Forms.py
class Entry(FlaskForm):
# (1)
# bullet = StringField(validators=[validators.DataRequired()])
bullet = CKEditorField(validators=[validators.DataRequired(), validators.Length(max=1000)])
class MyForm(FlaskForm):
entries = FieldList(FormField(Entry), min_entries=0)
plans = CKEditorField('Plans', [validators.InputRequired(), validators.Length(max=1000)])
app.js
$(document).ready(function() {
// (2)
// These are redundant but not working
CKEDITOR.replaceClass = 'ckeditor';
CKEDITOR.replaceAll( 'ckeditor' );
var addCount = 1;
$("#addNewField").click(function() {
var newInput = $("#entries");
newInput.append(GetDynamicTextBox("", addCount));
$("#entries").append(newInput);
addCount += 1;
listCKE();
});
// (3)
// CKE Documentation says to include a config instruction
// (in the form of) {{ ckeditor.config(name="misc_risks") }}
// This fn is my attempt at returning one of those for each added entry to the HTML
// This doesn't work, just returns raw text printed on the page
function listCKE() {
var items = ``;
for (var i=0; i<addCount; i++) {
items += `{{ckeditor.config(name="subdir`+i.toString()+`")}}`;
}
console.log(items)
document.getElementById("listcke").innerHTML = items;
}
});
function GetDynamicTextBox(value, addCount) {
return '<div>' + 'Entry ' + addCount + ': ' +
// (4)
// Tried replacing <textarea> with ckeditor create func; didn't work
// '{{ckeditor.create(name="subdir' + addCount + '")}}' +
// (2)
'<textarea class="ckeditor" name = "subdir' + addCount + '"type="text" value = "' + value + '"> </textarea> ' +
'<input type="button" value="Remove" class="remove" />' + '</div>' ;
}
$(function () {
$("#addNewField").click(function() {
$("#entries").append(GetDynamicTextBox("", addCount));
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
addCount -= 1;
});
});
webpage.html
<form method="POST" enctype="multipart/form-data">
{{form.csrf_token}}
<button type="button" id="addNewField">Add Entry</button>
{% for subdir in form.subdirs %}
{{ forms.render_field(subdir.name) }}
{% endfor %}
{{ form.entries() }}
{{ form.plans.label }} {{ form.plans() }}
<p><input type="submit" value="Submit"></p>
</form>
{{ ckeditor.load(pkg_type="basic") }}
{{ ckeditor.config(name="plans") }}
<!-- (4) This was used with the listCKE function in app.js. Didn't work, only returned raw text in {{}} to page -->
<!-- <div id="listcke"></div> -->
Flask's template engine jinja runs server-side while javascript runs on the client. For this reason, mixing expressions from both worlds, as you try to do during the execution time of the javascript code, is not possible.
The following example shows you one way to dynamically add fields that use the CKEditor. Here, unique name and id attributes are set for each field and the corresponding for attribute is set for the associated label.
from flask import (
Flask,
render_template,
request,
)
from flask_ckeditor import (
CKEditor,
CKEditorField
)
from flask_wtf import FlaskForm
from wtforms import FieldList, FormField
app = Flask(__name__)
app.secret_key = 'your secret here'
ckeditor = CKEditor(app)
class EntryForm(FlaskForm):
class Meta:
csrf = False
bullet = CKEditorField('Entry')
class MyForm(FlaskForm):
entries = FieldList(FormField(EntryForm), min_entries=0)
@app.route('/', methods=['GET', 'POST'])
def index():
form = MyForm(request.form)
if form.validate_on_submit():
print(form.entries.data)
return render_template('index.html', **locals())
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Index</title>
</head>
<body>
<form method="post">
{{ form.csrf_token }}
<div>
<button type="button" id="btn-add">Add</button>
</div>
<div id="entries">
{% for f in form.entries %}
<div>
{{ f.bullet.label() }}
{{ f.bullet() }}
<button type="button" class="btn-remove">Remove</button>
</div>
{% endfor -%}
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
{{ ckeditor.load() }}
{# Create a configuration for each CKEditor that already exists. #}
{% for f in form if f.type == CKEditorField -%}
{{ ckeditor.config(name=f.name) }}
{% endfor -%}
<script
src="https://code.jquery.com/jquery-3.7.1.slim.min.js"
integrity="sha256-kmHvs0B+OpCW5GVHUNjv9rOmY0IvSIRcf7zGUDTDQM8="
crossorigin="anonymous"></script>
<script>
$(document).ready(() => {
const entriesEl = $('#entries');
$('#btn-add').click(() => {
// If the button to add is clicked...
let ids = ['entries-0-bullet'];
const sel = 'textarea[name$="-bullet"]';
const entries = entriesEl.find(sel);
if (entries.length) {
// ... and there are already input fields ...
const lastEntry = entries.last().closest('div');
ids = $.map($(lastEntry).children(sel), function(elem) {
// ... extract the name attribute of the last input field
// and generate a new unique id from it.
const attr = $(elem).attr('name'),
s = attr.replace(/(\w+)-(\d+)-bullet$/, (match, p1, p2) => {
return `${p1}-${parseInt(p2)+1}-bullet`;
});
return s;
});
}
// For each id created a block with the new input field.
// Register a function to remove the block and configure the CKEditor.
$.each(ids, function(index, value) {
const newEntry = $.parseHTML(`<div>
<label for="${value}">Entry</label>
<textarea class="ckeditor" id="${value}" name="${value}"></textarea>
<button type="button" class="btn-remove">Remove</button>
</div>`);
$(newEntry).children('.btn-remove').click(function() {
$(this).closest('div').remove();
})
entriesEl.append(newEntry);
CKEDITOR.replace(value);
});
});
// Register a function to remove fields that already exist.
$('.btn-remove').click(function() {
$(this).closest('div').remove();
});
});
</script>
</body>
</html>