I need to make a "keywords" field on a front-end entry form that can create tags in the cms (Craft 2). I am fully aware of existing tickets regarding this issue like Brandon Kelly's but they're a little too ambiguous for me.
This is the classic tag field where you type a word, press spacebar, and a new tag appears, etc. I am aware that when my form submits, despite what's visual on the page, the submitted html needs to look something like this:
<input type="hidden" name="fields[fieldName]">
<input type="hidden" name="fields[fieldName][]" value="{tag 1 id}">
<input type="hidden" name="fields[fieldName][]" value="{tag 2 id}">
<input type="hidden" name="fields[fieldName][]" value="{tag 3 id}">
// etc
I've looked into many jquery plugins and they don't output this html pattern. Instead, they all basically create a single hidden input field with all your tags entered in the value attribute separated by commas like value="tag1, tag2, tag3, etc"
, (tag-it is one exception but it is outdated, buggy, and it always prints the tag's text in the value).
I'm not entirely sure how this all should work, but I'm guessing I need to write custom ajax so that when a tag is created, an ajax call uses the createTag
action to create the tag in the database before the form submits, since the saveEntry
form submission itself won't create the tag but merely link an existing tag to that entry.
Then, just as it's shown in Brandon's original answer, my js adds the hidden input formatted correctly in the successful response. If the user deletes a tag, I have to use the jquery plugin's removeTag
callback (or whatever the callback is) to then remove that hidden input.
However, where I'm getting confused is on these points:
- When a user deletes a tag on the front-end (let's say they made a typo), the js deletes the hidden input in the html, but the tag is already created in the database. Do I need to then somehow delete that tag in the database via ajax or just let my db rack up a bunch of unusable tags?
- Is it better to just do away with the hidden input approach, use a plugin to accept the comma-separated tags from one hidden input and do all the creating/checking for existing tags/etc on a
entries.onBeforeSaveEntry
as Ben seems to suggest in this ticket?
Can anyone offer up actual examples of what they did to handle tags on the front end? Maybe also some suggestions of solid jquery plugins in 2018 (many seem janky and not up to date)? And is my process of thinking outlined above incorrect in any way (I have very little idea what I'm doing)?
Current examples online are either for listing out existing tags the user can choose from with checkboxes or a multiselect (which is usually not the case on a form), or just showing some basic ajax. Any help and clarification would be greatly appreciated (and hopefully help someone else down the line).