smon

smon

I am experimenting with live view uploads for the first time, and I was wondering what is the recommended way of doing customized upload validations.

My simple example: I have an interface to upload files to a certain directory, and I want to warn the users of duplicate file names in their upload before they hit the submit button. My consume_uploaded_entries/3 would catch these cases, but I am expecting larger files being uploaded, so some feedback earlier would be nice.

So I could evaluate my uploads assign against a list of existing files by…
… setting :valid to false in the appropriate Phoenix.LiveView.UploadEntry structs.
… generating an appropriate error list for errors in the Phoenix.LiveView.UploadConfig struct.

It feels a little bit like screwing around with Phoenix LiveView implementation internals. Is this the way to do it? Did I miss some kind of helper function?

Showing Posts 1 to 3

smon

smon OP

I tried to implement my own entry validation, as described above, by extending the handle_info/3 that reacts to form changes.

See Uploads — Phoenix LiveView v1.2.5

But now I bumped into the issue: After evaluating the affected entries and setting appropriate errors, I am not allowed to use re-assign/3 the :upload key because it is a “reserved” one:

** (ArgumentError) :uploads is a reserved assign by LiveView and it cannot be set directly
    (phoenix_live_view 1.0.0-rc.6) lib/phoenix_component.ex:1324: Phoenix.Component.validate_assign_key!/1
    (phoenix_live_view 1.0.0-rc.6) lib/phoenix_component.ex:1275: Phoenix.Component.assign/3

So my initial reaction proved somewhat right: The LiveView authors do not want me to prod around in those internals. :stuck_out_tongue:

But: What can I do now? What seems to be missing is an option for allow_uploads/3 for passing a custom validator function.

smon

smon OP

Ok, I got it working by not using assign/3 which is a bit frightening. For anyone daring enough, here is the implementation.

My customized handle_event/3 looks like this.

def handle_event(
      "validate_selected_images",
      _params,
      %{
        assigns: %{
          uploads: %{images: selected_images} = uploads,
          existing_files: existing_files
        }
      } =
        socket
    ) do

  existing_names =
    Enum.map(existing_files, fn entry ->
      entry.file_name
    end)

  checked_images = mark_duplicate_names(selected_images, existing_names)

  assigns = Map.put(socket.assigns, :uploads, Map.put(uploads, :images, checked_images))

  {
    :noreply,
    Map.put(socket, :assigns, assigns)
  }
end

Here existing_files is a list containing application specific metadata structs. As you can see I use Map.put/3 to hack my way around the “reserved assign” restriction.

The function mark_duplicate_names/2 looks like this:

defp mark_duplicate_names(%Phoenix.LiveView.UploadConfig{} = upload, existing_names) do
  processed_entries =
    upload.entries
    |> Enum.map(fn %Phoenix.LiveView.UploadEntry{} =
                      entry ->
      if entry.client_name in existing_names do
        Map.put(entry, :valid?, false)
      else
        entry
      end
    end)

  upload
  |> Map.put(:entries, processed_entries) # replace file entries
  |> Map.put(
    :errors,
    Enum.map(processed_entries, fn %Phoenix.LiveView.UploadEntry{} = entry ->
      if entry.valid? do
        nil
      else
        {entry.ref, :name_duplicate}
      end
    end)
    |> Enum.reject(fn val -> is_nil(val) end) # create a list of error tuples for all entries with error
  )
end

Finally I implement a fourth error_to_string/1 function:

defp error_to_string(:name_duplicate), do: "A file with this name already exists"
smon

smon OP

Small update: In order to preserve the errors that got returned by Phoenix’ standard evaluation (size, type, upload count issues), I had to modify the function slightly.

defp mark_duplicate_names(%Phoenix.LiveView.UploadConfig{} = upload, existing_names) do
  processed_entries =
    upload.entries
    |> Enum.map(fn %Phoenix.LiveView.UploadEntry{} =
                      entry ->
      if entry.client_name in existing_names do
        Map.put(entry, :valid?, false)
      else
        entry
      end
    end)

  duplicate_name_errors =
    Enum.map(processed_entries, fn %Phoenix.LiveView.UploadEntry{} = entry ->
      previous_error? = Enum.any?(upload.errors, fn {ref, _msg} -> ref == entry.ref end)

      if entry.valid? or previous_error? do
        nil
      else
        {entry.ref, :name_duplicate}
      end
    end)
    |> Enum.reject(fn val -> is_nil(val) end)

  # Combine existing errors with additional ones evaluated here.
  errors = upload.errors ++ duplicate_name_errors

  upload
  |> Map.put(:entries, processed_entries)
  |> Map.put(:errors, errors)
end
— 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

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
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 & 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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews