rio517

rio517

Correct strategy for using datepicker attached to an input field with Liveview?

Hi!

I’m prepping to use flatpickr, a date picking library which attaches to a specific input field. I’m curious as to the best approach to integrate this with Liveview.

I’m using alpine.js to reveal the input field and to create the flatpickr instance on my input field. However, when Liveview handles the validation on change, it seems that flatpickr becomes “detached” from the target - the instance is still in memory, but cannot be opened. In the absence of a way to transfer the existing instance to the updated DOM element, I am assuming my best bet is to track and destroy() existing instance(s) and reinitialize via a client hook called on updated.

This might be exactly the right way to do this, but any other suggestions? My JS knowledge has atrophied a bit and I’m new to Liveview, so I’m just looking for validation that I’m not overlooking something.

Thanks so much for reading!

Marked As Solved

RodolfoSilva

RodolfoSilva

This is how I’m using today:

Put this inside the core_components.ex

  attr :id, :string, required: true
  attr :field, Phoenix.HTML.FormField,
    doc: "a form field struct retrieved from the form, for example: @form[:occurred_at]"
  attr :label, :string, default: nil
  def datetime_picker(assigns) do
    ~H"""
    <div id={@id} phx-update="ignore">
      <.input field={@field} phx-hook="DateTimePicker" type="text" label={@label} />
    </div>
    """
  end

Create a new Hook:

import flatpickr from "flatpickr"

/**
 * @type {import("phoenix_live_view").ViewHook}
 */
export const DateTimePicker = {
  mounted() {
    flatpickr(this.el, {
      enableTime: true,
      altFormat: "d/m/Y H:i",
      dateFormat: "Z",
      minuteIncrement: 1,
      time_24hr: true,
      altInput: true,
      static: true,
      wrap: false, 
    })
  },
} 

If you are usign TailwindCSS, put this inside you app.css

/**
 * Flatpickr fix full width
 */
.flatpickr-wrapper {
  @apply relative w-full;
}

And use like that

<.datetime_picker
  id="occurred-at"
  field={@form[:occurred_at]}
  label="Occurred at"
/>

This will work fine with :utc_datetime.

Also Liked

gdub01

gdub01

I’m currently doing it in an input_helper based off of https://dashbit.co/blog/dynamic-forms-with-phoenix:

  defp input(:datetime_select, form, field, opts) do
    date = if Map.has_key?(form.data, field) && !is_nil(Map.get(form.data, field)), do: NaiveDateTime.to_iso8601(Map.get(form.data, field)), else: ""
    content_tag :div, class: "control", phx_update: "ignore" do
      apply(Phoenix.HTML.Form, :text_input, [form, field, [class: "input #{state_class(form, field)}", phx_hook: "datetimeHook", value: date] ++ opts])
    end
  end
import flatpickr from "flatpickr";

export const datetimeHook = { 
  mounted() {
    flatpickr(this.el, {
      altInput: true,
      altFormat: "Y-m-d h:i K",
      dateFormat: "Z",
      enableTime: true,
      parseDate(dateString, format) {
        var wrongDate = new Date(dateString);
        var localizedDate = new Date(wrongDate.getTime() - wrongDate.getTimezoneOffset() * 60000);
        return localizedDate;
      },
    });
  }
}

Saving it as :utc_datetime.

I call it like:
<%= input f, :published_at, field_modifier: "", label: "Publish Date" %>

Though I forget why I have field_modifier: “”

sergio

sergio

My man do you know how much heartburn I suffered today trying to fix this god forsaken thing and your solution pulled me from the depths of hades out of the clutches of Mephistopheles himself?

rio517

rio517

That would probably apply to any datepicking library.

I re-read the docs and missed the fact that one could attach phx-update="ignore" to disable patching on specific DOM nodes. I added this to my input field’s parent and wallah! This obviates the need to manage specific instances.

Of course, if anyone has any better ideas, let me know!


That said, I’m surprised that Liveview patches the entire form when validating. I would have thought Liveview would focus on what was changed, not the entire form. I’m guessing that since Liveview patches elements based on changed assigns, that the round trip of the form_data is the change that causes the DOM patch.. ?? I’m hoping I can find some time to look into that more and maybe open a github issue to gather more info.

Where Next?

Popular in Questions Top

hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43806 214
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement