zamith

zamith

I’m creating a search form with filters and want both the query and the filters to change the URL. The filters and query can be set separately or together, and handle_params can already deal with either being empty.

What I’m doing is triggering a push_patch on events (filter click, form submit, clear search). Something like this:

  def handle_event("update_filter", %{"filter" => filter}, socket) do
    {:noreply,
     push_patch(socket,
       to: Routes.live_path(socket, Index, query: socket.assigns.query, filter: filter)
     )}
  end

  def handle_event("search", %{"query" => query}, socket) do
    {:noreply,
     push_patch(socket,
       to: Routes.live_path(socket, Index, query: query, filter: socket.assigns.filter)
     )}
  end

This works, but my “problem” is that I have to set all the url params every time I call push_patch. Is there any way to say append this param to the current path? Alternatively, is there any other design pattern I should be following to set this up?

Showing Posts 13 to 4

Sleepful

Sleepful

oh and I hit this issue while updating my deps so watchout if you are in the same boat: Liveview push_patch not working starting from version 3.3.0 · Issue #417 · phoenixframework/phoenix_html · GitHub

Sleepful

Sleepful

as of LiveView 18.18 this works well within a LiveView:

  defp self_path(socket, action, extra \\ %{}) do
    # find the name of the Routes function with:
    # `mix phx.routes`
    Routes.word_index_path(socket, action, extra)
  end

  def handle_event("some_event", params, socket) do
    url = self_path(socket, :index, %{"sort_by" => "foo"})
    socket = push_patch(socket, to: url)
    # updates URL to:
    # path?sort_by=foo
    {:noreply, socket}
  end

:slight_smile:

sb8244

sb8244

Author of Real-Time Phoenix

100% right! Let me post the latest code I had that worked great for me:

  def uri_path(uri, params) do
    params = Stringify.call(params) # utility function to stringify this map because Query params will be string only

    query =
      Plug.Conn.Query.decode(uri.query || "")
      |> Map.merge(params)
      |> Enum.reject(fn {_k, v} -> v == nil or v == "" end)
      |> Map.new()

    new_uri = Map.put(uri, :query, Plug.Conn.Query.encode(query))
    %{new_uri | scheme: nil, authority: nil, host: nil} |> URI.to_string()
  end

I put this in my app_web.ex file so that I could use it everywhere. Maybe that’s bad practice but it was common enough to warrant it.

seva

seva

Worth adding that instead of URI.decode_query/1 and URI.encode_query/1, you might want to use more robust Plug.Conn.Query.decode/1 and Plug.Conn.Query.encode/1, which do better encoding/decoding of lists in URL (e.g. ?ids[]=1&ids[]=2).

I.e.

URI.decode_query("ids[]=1&ids[]=2")
# => %{"ids[]" => "2"}

Plug.Conn.Query.decode("ids[]=1&ids[]=2")
# => %{"ids" => ["1", "2"]}
sb8244

sb8244

Author of Real-Time Phoenix

FWIW, you can also directly use the URI rather than calling the Routes helpers. The above code does this as well, but I wanted to provide a more concise version if you don’t need as many bells and whistles.

  def handle_params(_params, uri, socket) do
    {:noreply, assign(socket, :uri, URI.parse(uri))}
  end

  def handle_event("prev_page", _, socket = %{assigns: %{pager: %{page: page}, uri: uri}}) do
    current_params = URI.decode_query(uri.query || "")
    new_params = Map.put(current_params, "page", page - 1)
    to = uri.path <> "?" <> URI.encode_query(new_params)

    {:noreply, push_patch(socket, to: to)}
  end
Brainiac

Brainiac

for whoever that comes across this thread, @josevalim’s answer will not apply if you are using actions in your router declarations, as the route helper gets renamed to match the controller, and also results in different helper arities for different helpers.

Until the day comes where where we can use Phoenix.Controller helpers like current_path/2 to merge in params in liveview, you’ll have to update the URI manually.

You will need to modify step 2 of @josevalim’s answer to something like this:

def self_path(socket, extra) do
      # explained in notes 1
  uri = URI.parse(socket.assigns.uri)

    current_query_params =
      (uri.query || "")
      |> URI.decode_query()

    # explained in notes 2
    to_merge = Enum.into(extra, %{}) |> to_string_map()

    new_query_params =
      current_query_params
      |> Map.merge(to_merge)
      # explained in notes 3
      |> Enum.filter(fn {_k, v} -> v != "" end)

    encoded_params = URI.encode_query(new_query_params)

    %URI{
      uri
      | authority: nil,
        host: nil,
        scheme: nil,
        port: nil,
      # explained in notes 4
        query: if(encoded_params == "", do: nil, else: encoded_params)
    }
    |> URI.to_string()

end

Note that:

  1. You will have to store the uri in assigns.
  2. You will also need to convert the extra arg into a string map to correctly merge into the parsed query params, which will be string keys. This is represented by a utility function to_string_map/1 which simply does a list comprehension to convert the atom key to a string.
  3. You will need to filter out empty string values if extra contains a nil value.
  4. You will need to check if the encoded params is an empty string, and if so, set the :query key of the new URI to nil. This new %URI{} struct needs all keys except :path to be replaced with nil.
josevalim

josevalim

Creator of Elixir

Here is how I solved it in my app:

  1. I store the params in handle_params as part of the assigns:

     def handle_params(params, url, socket) do
       # You could store the params as is but I like to store
       # only what has been parsed/validated.
       params = parse_params(params)
       {:noreply, assign(socket, :params, params)
     end
    
  2. Create a helper called self_path:

     def self_path(socket, action, extra) do
       Routes.live_path(socket, __MODULE__, action, Enum.into(extra, socket.assign.params))
     end
    
  3. Now I do:

     push_path(socket, to: self_path(socket, :search, %{"sort_by" => "foo"}))
    
19
Post #7
Telaia369

Telaia369

I have the same problem. Desperate for a solution… https://forum.elixirforum.com/t/cleaner-push-patch-and-handle-params/35583

zamith

zamith OP

I’m using Surface, but you can do the same with regular LiveView.

sreyansjain

sreyansjain

How to try it. I tried generating but no search feature got generated.

mix phx.gen.live Masters Item items item

No search thing got generated.

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
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
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
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
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews