Phoenix live view form auto submit

Hello everyone!

At the moment I render a page use phoenix live view

View

      <%= f = form_for :select, "#", [phx_submit: :select, id: "update-year"] %>
        <%= select f, :year,    
           year_select_options,
           selected: @filter_year,
           onchange: "this.form.submit();",
           class: "form-select mr-4" %>        
      </form>

Controller

   def handle_event("select", %{"select" => %{"year" => year}}, socket) do
       some_logic()
   end

Expected:
Remove the submit button and when select updated, this form will auto submit.

Error:
no route found for POST /current_path

Anyone known how to handle this?

Thanks!

Currently you are submitting the form using the “standard” HTML submit behavior (even if it’s done in the JS onchange) which will post to the current path.

LiveView provide a phx-change event that works on forms.
Just put phx-change="select" within the attributes of your form tag. Then it will be the LiveView communication that will kick in…

Edit: typo

2 Likes

Thank you! It helps!

It’s my pleasure…

If you’re not aware there is a great course about LiveView offered for free by Pragmatic Studio!
The course is still not yet fully complete right now. Almost the half is done and it’s very great so far! (and without doubts until the end!)

You can check the course here.

And also take a look at the post from @mikeclark (the author) about the course here.

2 Likes