Perhaps the solution would be to have two separate CMS collections:
A “conversations” database for what I described above
and
A “messages” database where each item is one message, and is referred to the correct “conversations” item
Could work, but normaly you need just one collection.
The DB-Fields will be generated automatically if you change the TITLE of the FIELD.
The only problem will be, to determine the type of the field.
So the code to add new fields to an item would be something like this? :
onMessageSubmitted → add to field_id: "message1" UNLESS "message1" already has a value, then add to field_id: "message2", UNLESS "message2" already has a value etc. etc.
Obviously the code has to be structured such that I shouldn’t have to write endless code, haha
What do you think of this code? ChatGPT suggestion. Looks like it has some flaws.
import wixData from 'wix-data';
$w.onReady(function () {
// Add an onClick event handler to the submit button
$w("#submitButton").onClick(submitMessage);
});
async function submitMessage() {
const messageText = $w("#messageTextBox").value.trim(); // Get the message text from the text box and trim leading/trailing spaces
// Loop through possible message fields
for (let i = 1; ; i++) {
const fieldName = "message" + i;
const existingItem = await wixData.query("YourCollectionName")
.eq(fieldName, "") // Check if the current message field is empty
.find();
// If no existing item with empty field found, continue to the next field
if (existingItem.items.length === 0) {
continue;
}
// If an empty field is found, update the field with the message
const newItem = {
[fieldName]: messageText
};
await wixData.update("YourCollectionName", newItem); // Update the message field with the new text
break; // Exit the loop
}
// Clear the text box after submission
$w("#messageTextBox").value = "";
}
Field 1, 2, 3, maybe four, will have some user id’s, maybe e-mail of the two people in the conversation. That’s not my main question, because I have ideas for that.
Main question:
The rest of the fields will be message fields.
Field 5: First message
Field 6: Second message
Field 7: Third message
Field 8: Fourth message
Field 9: Fifth message
… continuing as long as possible !
So – I’m trying to write some code where → USER submits message → Add message to [field 5] IF [field 5] is EMPTY → ELSE add the message to [field 6] IF [field 6] is EMPTY → ELSE add the message to [field 7] IF [field 7] is empty → ELSE … (you get the idea) … continuing indefinitely.
So I’m trying to create a LOOP with the code, so that I don’t have to write 10,000 lines of code mentioning 10,000 possible fields to add the message to.