DestroyedSoul

DestroyedSoul

Hello,

I am trying to implement more or less basic search screen. I use Phoenix/LiveView.
I’ve come across an issue that means either I chose the wrong approach, or I suck with forms (most likely - both).

The screen is super simple at this point: search bar in the middle, filters to the right, search results in the middle.
I put all three of these elements into the single form, like this:

<div class="container">
  <.form
    for={@search_form}
    phx-change="apply_filters"
    phx-submit="search"
    class="..."
  >
    <.search_bar field={@search_form[:query]} />

    <div class="flex flex-col md:flex-row">
      <!-- Filters Column -->
      <div class="...">
        <.filters_section
          form={@search_form}
          filter1={filter1_list()}
          filter2 ={filter2_list()}
          filter3 ={filter3_list()}
        />
      </div>
      <!-- Search Results Column -->
      <div class="w-full md:w-3/4">
        <.search_results results={@results} />
      </div>
    </div>
  </.form>
</div>

filter1, filter2, filter3 is sections on the right side of the screen, each consisting of several options. Consider, the list of brands, for example, list of locations etc. They all are multi selects.

My idea is to build the screen from the endpoint. The endpoint would look something like /search?q="..."&f1=...&f2=...
So, I put this into the live view code (for now, ignoring filters, only supporting query)

def mount(_params, _session, socket) do
    socket =
      socket
      |> assign(search_form: to_form(Search.make_search_form()))
      |> assign(:results, [])

    {:ok, socket}
  end

  def handle_params(params, _uri, socket) do
    query = params["q"] || ""
    
    filters = []

    search_form = Search.make_search_form(query, filters)

    socket =
      socket
      |> update(:search_form, fn _ -> to_form(search_form, as: :search_form) end)
      |> update(:results, fn _ -> search_results(search_form) end) # this builds and executes Ecto query returning the list of results

    {:noreply, socket}
  end

Then, when the search button is pressed I do this:

def handle_event("search", %{"search_form" => search_form}, socket) do
    {:noreply, push_patch(socket, to: "/search?#{build_search_query(search_form)}")}
  end

defp build_search_query(search_form) do
    filter1 = []
    filter2 = []
    filter3 = []

    "q=#{search_form["query"]}&f1=#{filter1}&f2=#{filter2}&f3=#{filter3}"
  end

So far, this works ok. The search bar has the correct text at all times, the results are filtered properly, the filters checkboxes are enabled and disabled (UI-wise) without any problems.
The multi-select is implemented like this:

  attr :form, Phoenix.HTML.Form, required: true
  attr :field, Phoenix.HTML.FormField, required: true
  attr :options, :list, required: true

  defp multi_select(assigns) do
    ~H"""
    <div class="...">
      <%= for option <- @options do %>
        <label class="...">
          <input
            type="checkbox"
            name={"#{input_name(@form, @field.field)}[]"}
            value={option}
            checked={option in @field.value}
            class="..."
          />
          <span class="...">{option}</span>
        </label>
      <% end %>
    </div>
    """
  end

and is added to the parent tag like this:

  <div>
        <h3 class="...">Filter Name, e.g. Brands</h3>
        <.multi_select
          form={@form}
          field={@form[:param1]}
          options={@filter1}
        />
     </div>

So far, so good.
Now, I would like for filters to take part in Ecto logic as well.
I do literally 3 changes.

  1. Add handle_event function:
  def handle_event("apply_filters", %{"search_form" => search_form}, socket) do
    {:noreply, push_patch(socket, to: "/search?#{build_search_query(search_form)}")}
  end
  1. Modify how I build the search query:
defp build_search_query(search_form) do
    filter1 = convert_list_to_string(search_form["filter1"])
    filter2 = convert_list_to_string(search_form["filter2"])
    filter3 = convert_list_to_string(search_form["filter3"])

    "q=#{search_form["query"]}&f1=#{filter1}&f2=#{filter2}&f3=#{filter3}"
  end

The result of this function looks good, e.g. "q=test&f1=brand1,brand2,brand3..." etc
3. Modify the handle_params function:

def handle_params(params, _uri, socket) do
    query = params["q"] || ""
    
    filters = %{
      :filter1 => String.split(params["f1"] || "", ","),
      :filter2 => String.split(params["f2"] || "", ","),
      :filter3 => String.split(params["f3"] || "", ",")
    }

    search_form = Search.make_search_form(query, filters)

    socket =
      socket
      |> update(:search_form, fn _ -> to_form(search_form, as: :search_form) end)
      |> update(:results, fn _ -> search_results(search_form) end) # this builds and executes Ecto query returning the list of results

    {:noreply, socket}
  end

What happens after this is the following:
If I enter the screen via /search endpoint and then start enabling checkboxes - they work fine.
If I enter the screen via the pre-built search query, all looks good too: the text in the search box is fine, and the checkboxes that should be enabled, are.

In both cases, problem starts when I try to disable a checkbox. It becomes super buggy: enabled/disabled state does not correspond to the params in the query, and at some point the query starts having the same param several times, e.g. f1=brand1,brand2,brand1.

I would welcome any advice.

Showing Posts 1 to 4

joshamb

joshamb

I’d suggest reading the following:

This also goes through doing what you desire, but with a less hard-cody build_search_query.

It’s a little outdated, but using ‘verified routes’ you can just do the following:

~p"/search?#{params}"

And it does the rest.

In regards to your problem, it’s likely you will find the booleans are becoming strings, ie "false" rather than false in the params of your handle_params.


In regards to your form, it’s not gonna ‘fix’ anything but I wouldn’t suggest putting your search results in their too, you should keep it elsewhere.

joshamb

joshamb

And if you wanted to further improve your solution, you could use an ‘embedded_schema’ to create your filter, and just past the .changes from it’s changeset into the URL to reduce clutter.

This is rather than the plain map you are passing into to_form

cmo

cmo

And use assign instead of update if you’re setting rather than updating the value.

DestroyedSoul

DestroyedSoul OP

Hello,
Thanks for the article suggestion.
It indeed does what I want to achieve as well.
I compared their logic with mine, and I have to say it’s pretty much the same (except for my build_search_query etc that you mentioned).
I tried to play around with the code to make it look more like theirs, but that did not help much.
As well as using ~p"/search?#{params}"

What I see is that in the article they only have string params, while I have lists.
It all works with just the search query (which is string), until I start trying to parse lists too.
Even ~p"/search?#{params}" returns string like "search/?query=test&f1[]=value1&f1[]=value2", whereas I would expect something like "/search?query=test&f1=value1,value2"

it’s likely you will find the booleans are becoming strings, ie "false" rather than false in the params of your handle_params .

I don’t have booleans yet anywhere, just string query (which works fine) and lists of strings for filters.

— 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
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
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
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