Liveview child form component triggers event against parent form component and not itself

Hello all,

I seem to be hitting an issue in a phoenix liveview app where a child live_component is triggering the parent form’s validate event instead of the child’s named event and I can’t figure out why. I initially thought it’s maybe a regression of this issue and I did have some outdates JS it seemed so I did a mix deps.clean phoenix_live_view and the phoenix_live_view.js file now seems to be updated, however, I’m still seeing the event trigger against the parent form.

Does the liveview form component not allow for embedding children live_components? Or am I missing something?

I’m not sure this is the best approach, but appreciate if someone could point out what the issue might be or maybe even a better way to handle this and thanks in advance :pray:

<div>
    <.form
    :let={f}
    for={@changeset}
    id="parent-form"
    phx-target={@myself}
    phx-change="validate"
    phx-submit="save">

      <.live_component
        id="search-item"
        module={App.Forms.ChildComponent} />

    ...
    </.form>
</div>

the child component is ignored:

defmodule App.Forms.ChildComponent do
  use App, :live_component

  @impl true
  def update(assigns, socket) do
    {:ok,
     socket
     |> assign(assigns)}
  end

  @impl true
  def handle_event("search-item", %{"item" => item}, socket) do
    {:noreply, assign(socket, :item, item)}
  end

  def handle_event("confirm-item", %{"item" => item}, socket) do
    {:noreply, assign(socket, :item_confirmed, item)}
  end

  def render(assigns) do
    ~H"""
    <div>
    <.form
      id="child-form"
      phx-target={@myself}
      phx-change="search-item"
      phx-submit="confirm-item" >
      <div class="form-control">
        <div class="input-group">
          <input type="text"
                 name="item"
                 class="input input-bordered"
                 value={@item}
                 autocomplete="off" />

          <button class="btn btn-square">
          ...

If you make nested forms, all children forms are ignored.
Check the html in devtools of your browser.

1 Like

I think you should move the phx-target={@myself} to the child component.

Interesting, the parent and child components have different ids and their respective data-phx-component is also different but the child form component was ignored/not rendered and thus nothing targets that child component’s events … hmm, seems I’ll have to build this manually.

@bdarla there’s already a phx-target={@myself} in the child component but the nested .form component was completely ignored (not rendered) as pointed out by @nallwhy. I was able to get this wrapper to work by simply unwrapping the child .form component although this means a little more manual work to get it all wired up :slight_smile:

Thanks to both of you for your responses!

FWIW nested html form tags is technically invalid html, so things may not work as intended.

3 Likes