rio517

rio517

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!

Showing Posts 1 to 10

shortlyportly

shortlyportly

Hi @rio517

I’m just curious as I’m about to integrate a datepicker into my application. Is this an issue with flatpickr itself. Have you tried other datepickers and do you get the same issues?

cheers

Dave

rio517

rio517 OP

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.

shortlyportly

shortlyportly

Great to know about the phx-update=“ignore”. Also I think you are right about the round trip for form data as the entire form is passed back and forth even when validating a single field.

I’m going to be a bit cheeky and ask if you are able to provide your implementation of flatpickr with live-view?

cheers

Dave

rio517

rio517 OP

I’m not sure if this is a shining example of how to do things - as mentioned I still wonder if there are easier ways. Here is a simplified example of where I am ending up - but note that I’m still in the middle of building a multi-step form using Alpine.

// js bits

let liveSocket = new LiveSocket("/live", Socket, {
  params: {_csrf_token: csrfToken},
  dom: { // for alpine.js
    onBeforeElUpdated(from, to){
      if(from.__x){ window.Alpine.clone(from.__x, to) }
    }
  }
})

window.skillFrequency = function () {
  return {
    flatpickrInstance: null,
    setUpFlatpicker(frequency){
      this.flatpickrInstance?.destroy();
      this.flatpickrInstance = setupFlatpickr.build(frequency);
    }
  }
}

window.setupFlatpickr = {
  settings: {
    one_time: {
      fieldWrapperClass: ".flatpickr-onedatetime",
      options: {static: true, minDate: "today"  }
    }
  },
  build (targetFrequency) {
    if (targetFrequency in this.settings) {
      var targetSettings = this.settings[targetFrequency]

      var options = {
        ...targetSettings.options,
        ...{appendTo: document.querySelector(targetSettings.fieldWrapperClass)}
      }
      return flatpickr(targetSettings.fieldWrapperClass + " input", options)
    }
  }
}

// the form…

<%= if connected?(@socket) do %>
  <%= f = form_for @changeset, "#", id: "subskill-form", phx_change: "validate", phx_submit: "save", "x-data": "skillFrequency()"  %>
    <div class="field flatpickr-onedatetime">
      <%= label @form, :one_time_at %>
      <div class="control" phx-update="ignore">
        <%= text_input @form, :one_time_at, class: "input", placeholder: "Select Date" %>
      </div>
      <%= error_tag @form, :one_time_at %>
    </div>
  </form>
<% end %>
overcomeoj

overcomeoj

Duck question, when you look at the debug log, is it patching the whole form or the whole view? maybe something else is triggering the full patch?

shortlyportly

shortlyportly

Thanks @rio517 - I’ll study the code as it is certainly something I need to do. cheers.

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: “”

rio517

rio517 OP

It is patching the whole form. This even occurs in a newly generated app on :phoenix, "1.5.8", with nothing else in it.

> mix phx.new shiney --live
> cd shiney
> mix ecto.create
> mix phx.gen.live Publication Author authors name:string color:string count:integer
> mix ecto.migrate
> mix phx.server

Screenshot:

overcomeoj

overcomeoj

I wounder if because the @changeset changes, the f = form_for .. changes, so all the builder’d elements change too?

cenotaph

cenotaph

I have hit the same problem with bulma calendar.

no matter what I do phoenix destroys the calendar when I open a modal or add new object.

I can’t add them without the phx-update=ignore

I can re-add them with this listener but then I will get multiple instances on it.

I am going to investigate jsOps when I have more time

window.addEventListener("phx:page-loading-stop", info => doStuff() )

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
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
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
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
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
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
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
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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews