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

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
jaybe78
Hello, I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter). The diffic...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
matt-savvy
Anyone here using Honeybadger? My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of Bandit.HTTPError...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New
webofbits
Aludel - LLM Evaluation Workbench Aludel is an embeddable Phoenix LiveView dashboard for evaluating and comparing LLM prompts across mult...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews