Phoenix HTML Form associate existing Ecto data

Hi,

I have a Live View Form with a search text field which allows users to find a currencies Pair (Ecto entity) from its symbol attribute. The form should allow the insertion of a Setting in db, the pair being one of its associations.

When the form live view is mounted, a list of the first 20 pairs are fetched from db and assigned to the socket to be displayed in a .
When the user starts typing the search field, a new list of Pair is fetched with the query and the is updated consequently to allow the user to ultimately select a value in this list.

I’m not sure how to update the Setting Changeset so the Pair entity is correctly associated to it when persisted in database.

Currently I’m updating the form data during form validation :

def handle_event([…]) do
  changeset =
    socket.assigns.session
    |> Backtests.change_session(session_params)
    |> Map.put(:action, :validate)

  socket =
    case fetch_pairs(symbol_query) do
      [pair] ->
        # single search result => association it
        setting_changeset =
          changeset
          |> get_assoc(:setting)
          |> put_assoc(:pair, pair)

        changeset =
          put_in(changeset.changes.setting, setting_changeset)

        socket
          |> assign_form(changeset)
          |> assign(:symbols, [])

      symbols ->
        # multiple search results => keep searching (clean association maybe?)
        socket
        |> assign_form(changeset)
        |> assign(:symbols, symbols |> Enum.map(& &1.symbol))
    end 
end

To clarify the full data structure : Session has_one → Setting has_one → Pair

The issue I’m facing is when the user click a “pre-validation” button of the form, the parameters map received in the click event callback does not contain the user selected Pair entity since it has not been added there and I’m not sure if I should get it from the form data…

Does anyone have any idea how to improve this situation ?

I am often struggling with Ecto and Forms… :smiling_face_with_tear: I wish there would be more resources available about this subject, especially when the form is not a direct representation of the Ecto data structure.

Have a nice day ! :sunglasses: