k-p

k-p

I’m trying to allow a user to add tags to a parent using a has_many relationship. I’d like to offer ‘suggested’ tags that they can click and these are added to the form data. These are simple, single, text-entry forms.

I have a dynamic form using inputs_for with a button to add new, blank, form entries and remove existing values, per the standard Liveview documentation. I can add new tags, which is a single input, and this works as expected.

How can I programatically add new inputs_for entries with data in the form entry?

Can I use the value=“new” to set a value I can capture instead?

I’ve tried putting suggested tags as buttons with phx-click and handlers to capture the suggested tag value and put them in the parent struct as a struct item rather than param map, but I can’t work out how to have these render in the inputs_for in the same way as the ‘new’ tags.

eg, using the example code:

<.inputs_for :let={ef} field={@form[:emails]}>
  <input type="hidden" name="mailing_list[emails_sort][]" value={ef.index} />
  <.input type="text" field={ef[:email]} placeholder="email" />
  <.input type="text" field={ef[:name]} placeholder="name" />
  <button
    name="mailing_list[emails_drop][]"
    value={ef.index}
    phx-click={JS.dispatch("change")}
  >
    <.icon name="hero-x-mark" class="w-6 h-6 relative top-2" />
  </button>
</.inputs_for>

<input type="hidden" name="mailing_list[emails_drop][]" />

<button type="button" name="mailing_list[emails_sort][]" value="new" phx-click={JS.dispatch("change")}>
  add more
</button>

How could I have a button that would append an ef form item with an email value of ‘boop@boop.com’?

Showing Posts 1 to 3

LostKobrakai

LostKobrakai

sort_param doesn’t support such a usecase. It works from a mapping on a single form key to indexes, so there’s no way to pass any additional data.

The approach taken in One-to-Many LiveView Form | Benjamin Milde might work for you.

k-p

k-p OP

That link was great and well written. Thanks! Now all working.

The trick in the link above to get the form data and update the changeset in a handler that doesn’t receive the form params, using get_assoc/put_assoc, worked great. I can keep all the existing code & behaviour the same, so a neat bonus is still getting deletion of dynamic inputs for ‘free’ from drop_param.

So to programatically add new inputs with data, you just need a button with a value and one additional handler:

 def handle_event("add_tag", %{"value" => tag}, socket) do
    new_tag = %SkillTag{
      tag: tag
    }

    socket =
      update(socket, :form, fn %{source: changeset} ->
        existing = Ecto.Changeset.get_assoc(changeset, :skill_tags)
        changeset = Ecto.Changeset.put_assoc(changeset, :skill_tags, [new_tag | existing])
        to_form(changeset)
      end)

    {:noreply, socket}
  end
nduitz

nduitz

I know this post is pretty old nevertheless I wanted to share my approach for this.

I use sort_param to achieve adding an item of the same type with different configurations.

Here is what I do to achieve this:

~H"""
<.inputs_for :let={f} ...>
  <.button name="sort_param[]" value={JSON.encode!(%{attribute: "initial_attribute_value"})}>Add new entity</.button>
  <.input type="hidden" field={f[:_existing_relation]} />
</.inputs_for>
"""

Then I use a dedicated changeset function header to handle the add-case

def changeset(entity, %{"sort_param" => [initial_attrs]} = attrs) do
  initial_relation_attrs = JSON.decode!(initial_attrs)

  entity
  |> cast(attrs, [])
  |> cast_assoc(:relation, sort_param: :sort_param, with: &MyRelation.changeset(&1, &2, initial_relation_attrs)
end

def changeset(entity, attrs) do
  # handle other change
end

An last but not least I use a dedicated changeset function header to handle changing the relation:

def changeset(relation, %{"_existing_relation" => _} = attrs, _initial_attrs) do
  # we can ignore initial_attrs for this changeset since this is an existing relation

  ...
end

def changeset(relation, _attrs, initial_attrs) do
  # attrs is always empty when adding, use initial_attrs instead to build the changeset
  ...
end

Hope this helps anyone who might find this post later :slight_smile:

— All posts loaded —

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews