5

I use the following entry form (front-end): https://craftcms.com/docs/templating/entry-form

How can I add a tags-field to this entry form?

1 Answer 1

4

You would need to add inputs to the form based on your Tags field handle, with values set to the tag IDs that should be selected.

Here’s a very simple example – it creates a big checkbox list of all the existing tags:

<div id="tags">
    {% for tag in craft.tags.group('myTagsGroup').limit(null) %}
        <label>
            <input type="checkbox" name="fields[myTagsField][]" value="{{ tag.id }}">
            {{ tag.name }}
        </label>
    {% endfor %}
</div>

Note that it is not possible to create new tags directly from a Tags field. If you want users to also be able to create new tags from your form, that will require a little Javascript.

<a id="new-tag">+ New tag</a>

<script type="text/javascript">

    $('#new-tag').click(function()
    {
        var name = prompt('What’s the new tag name?');

        if (!name) return;

        var data = {
            groupId: 1,
            name: name
        };

        $.post('/actions/tags/createTag', data, function(response)
        {
            if (response.success)
            {
                $('<label>' +
                      '<input type="checkbox" name="fields[myTagsField][]" value="'+response.id+'" checked="checked"/> ' +
                    name +
                  '</label>').appendTo($('#tags'));
            }
            else
            {
                alert('Unable to create that tag.');
            }
        });
    });

</script>

Make sure to set the correct groupId in that data object. You can find your tag group’s ID by looking at the URL when editing the group’s settings within Craft’s CP.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.