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

itzmidinesh
Hi all, I’m working on a Phoenix project where I need to make external HTTP requests and I’m trying to choose between Req and HTTPoison....
New
yarrichar
I’m very new to Elixir, so sorry if this is a silly question: I am wondering what happens to the mailbox of a process when the machine i...
New
pragdave
How do I tell Hologram not to escape HTML when substituting into templates? {Textile.render(@product.long_description)} escapes the HTM...
New
Fl4m3Ph03n1x
Background When trying to execute mix release on a Windows 11 machine for a Phoenix project I get the following error: * assembling mark...
New
rlipscombe
I’d like to create a file with 600 permissions (rw-------), but there’s a race condition if I create it and then change the permissions. ...
New
saleyn
Is there a way to import record definitions in the iex shell for pretty printing (similar to the rr command in the erl shell)? This woul...
New
rlipscombe
When I use Mix.install with a git dependency, using git@github.com:... how do I change the SSH identity used? I’ve got two Github accoun...
New

Other Trending Topics Top

dominicletz
Hey there, I haven’t seen a list of useful Elixir specific skills for the popular AI tools yet so I’m starting one here with my first. ...
New
raa-ziq
Hi everyone :waving_hand: I wanted to share something I’ve been building — NowBlind, a random chat app designed to help people discover ...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New
kip
Localize is the next generation localisation library for Elixir. Think of it as ex_cldr version 3.0. The first version will be released ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews