Phoenix LiveView how to add more values to session when form is submitted?

I am trying to add the extra key-value pair "list_id" => @list.id in addition to what the form sends by default to the session that will be passed into def handle_event("save", session, socket). How can I accomplish this?

I have tried using JS.push in phx-submit, but that has no effect.

list_live.html.heex:

def handle_event("save", session, socket) do
    #
end

form.html.heex:

<%#  form.html.heex %>

<.form
  let={f}
  for={@changeset}
  phx-change="validate"
  phx-submit={Phoenix.LiveView.JS.push("save", value: %{"list_id" => @list.id})}
  phx-value-list_id="1"
>
  <%= if @changeset.action do %>
    <div class="alert alert-danger">
      <p>
        Oops, something went wrong!
      </p>
    </div>
  <% end %>

  <%= label(f, :content) %>
  <%= text_input(f, :content) %>
  <%= error_tag(f, :content) %>

  <button type="submit">
    Save
  </button>
</.form>

Did you mean “passed into def handle_event” ?

If so, this works:

<.form
  let={f}
  for={@changeset}
  phx-change="validate"
  phx-submit="save"
>
  <%= hidden_input f, :list_id, value: @list.id %>
</.form>
1 Like

Just out of curiosity, with that, the resulting session passed into handle_event is:

%{"list_item" => %{"content" => "", "list_id" => "42"}}

Is there a way to instead pass in a map like this upon submitting the form:

%{"list_id" => 42,"list_item" => %{"content" => ""}}

It’s not a session that is passed to handle_event, it is a params map.

You can structure the changeset any way you like really, with a schemaless changeset or an embedded changeset, but you’ll need to nest/embed that list_item.

1 Like