Add, remove, and append entries to an entries field via frontend form

Sofia: 2 weeks ago

I'm making a one-button form, to add an entry to an entries field. Adding seems pretty straightforward, but it overwrites any previous entry that occupied the entries field. How would I append an entry to the entries field, or remove an entry?

<form method="post" accept-charset="UTF-8">
  {{ getCsrfInput() }}
  <input type="hidden" name="action" value="entries/saveEntry">
  <input type="hidden" name="entryId" value="{{ }}">
  <input type="hidden" name="redirect" value="{{currentUrl}}">
  <input type="hidden" name="fields[tournamentTeams][]" value="{{}}">

  <input type="submit" value="Add {{team.title}} to this Tournament">

My guess is, I will have to populate the entries field input value with the already-added entries to append the entry, and do the same kinda deal upon removing the entry- no idea how I would detect and remove the entry though!

Micah: 2 weeks ago

You guessed right, you have to set all already added entries again. To do this, just have some Twig logic when outputting the fields:

{% for currentTeam in entry.tournamentTeams %}
    <input type="hidden" name="fields[tournamentTeams][]" value="{{ }}">
{% endfor %}
<input type="hidden" name="fields[tournamentTeams][]" value="{{ }}">

To remove the entry:

{% for currentTeam in entry.tournamentTeams if != %}
    <input type="hidden" name="fields[tournamentTeams][]" value="{{ }}">
{% endfor %}

Update: What I'm not sure about is if the above code works when trying to remove the last remaining entry. If it doesn't work I'd try and add something like this:

{% if (entry.tournamentTeams|length == 1) and (entry.tournamentTeams.first().id == %}
    <input type="hidden" name="fields[tournamentTeams]" value="">
{% endif %}